¿Cuál es una forma eficaz de asociar modelos de publicación, comentario, usuario y voto en Rails?

Right now, I have three models Post, Comment and User (using Idear) associated as follows:

post.rb:

class Post < ActiveRecord::Base
  attr_accessible :title, :content, :total_votes

  validates :title,   :presence => true,
                      :length   => { :maximum => 30 },
                      :uniqueness => true
  validates :content, :presence => true,
                      :uniqueness => true

  belongs_to :user
  has_many :comments, :dependent => :destroy
end

comment.rb:

class Comment < ActiveRecord::Base
  attr_accessible :content, :user_id

  belongs_to :post, :counter_cache => true
  belongs_to :user
end

user.rb:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable
  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username

  validates_presence_of :username
  has_many :posts, :dependent => :destroy
  has_many :comments, :dependent => :destroy

  def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info
    if user = User.where(:email => data.email).first
      user
    else # Create a user with a stub password. 
      User.create!(:email => data.email, :password => Devise.friendly_token[0,20]) 
    end
  end
end

I want to add a fourth model called Votar con las siguientes condiciones:

  1. Ambos mensajes y comentarios can be voted (up and down) and show the total/sum.
  2. ¡Cada post will have many votes (up and down) and show the total/sum.
  3. ¡Cada comentario will have many votes
  4. The ID of the user should be stored each time he or she votes so I can restrict one vote per user and show the ID/name of the users who voted (not sure where to store it)

Now, I'm not sure if this is a good occasion to use asociaciones polimórficas y/o contador de caché.

What's an efficient way of associating these Post, Comment, User and Voting models? (If possible, I would like to see how the migration would look like)

preguntado el 01 de febrero de 12 a las 22:02

1 Respuestas

This is a perfect textbook example of where a asociación polimórfica sería útil.

Tus votes table migration would look like this:

create_table :votes do |t|
  t.references :votable, :polymorphic => true
  t.references :user
  t.integer :polarity
  t.integer :total
end

This would create a table with this schema:

id INTEGER
votable_id INTEGER
votable_type VARCHAR
user_id INTEGER
polarity INTEGER
total INTEGER

Aquí, user_id would be the person who cast the vote, polarity would be either '1' for an upvote or '-1' for a downvote (this lets you just sum the polarities to get upvotes and downvotes to cancel), votable_type would contain what the vote is for (Post or Comment), votable_id would contain the id of the thing the vote is for, and total would keep a running total of the vote sum (for efficiency).

Then your models would look like this:

class Vote < ActiveRecord::Base
    belongs_to :votable, :polymorphic => true
    belongs_to :user

    before_create :update_total

    protected

    def update_total
        self.total ||= 0
        self.total += self.polarity
    end
end

class Post < ActiveRecord::Base
    has_many :votes, :as => :votable
end

class Comment < ActiveRecord::Base
    has_many :votes, :as => :votable
end

class User < ActiveRecord::Base
    has_many :votes
end

Respondido 02 Feb 12, 04:02

Thanks a lot! Yeah I need a total of all votes in each post and comment. So I just need to add total INTEGER a vote.rb model file? - alexchenco

Could you also please show me how the migration would look like? - alexchenco

@user734290, sorry, I meant to add the migration and forgot to. Updated. - Ben Lee

Note that you have to update total manually ever time a vote is cast. - Ben Lee

@ user734290, consulte el before_create callback I added to the Vote model in my answer. That's how'd you keep a running sum in total. - Ben Lee

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.