wyc
wyc

Reputation: 55273

What's an efficient way of associating Post, Comment, User and Vote models in Rails?

Right now, I have three models Post, Comment and User (using Devise) 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 Vote with the following conditions:

  1. Both posts and comments can be voted (up and down) and show the total/sum.
  2. Each post will have many votes (up and down) and show the total/sum.
  3. Each comment 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 polymorphic associations and/or counter cache.

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)

Upvotes: 1

Views: 253

Answers (1)

Ben Lee
Ben Lee

Reputation: 53319

This is a perfect textbook example of where a polymorphic association would be useful.

Your 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

Here, 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

Upvotes: 1

Related Questions