Search code examples
ruby-on-railsrubyruby-on-rails-3counterrating

Rails: A Rating Up or Down Counter, Lost


I am currently trying to create a rating counter that has a up or down feature to it. I am confused to if I should add a column to my post to show that a person likes the post or create a separate model to show the rating counter but the counter belongs to the post. Something along the lines of Reddit or even Stackoverflow's. Also, how would I start on this rating counter, to whichever method is the right method? Thank you everyone.

Edit - Currently stuck on how to move on from here

Rating

class Rating < ActiveRecord::Base
  attr_accessible :post_id, :user_id, :rating
  has_many :post
  has_many :users

  validates :post_id, presence: true

end

Rating Controller

class RatingController < ApplicationController

  def create
    @post = Post.find(params[:id])
    @post.rating_count = @post.rating_count + 1
  end
end

Rating Form

<%=form_tag @rating do %>
<%=submit_tag :Rating%>
<%end%>

Solution

  • You should create a separate model, which will store user_id, post_id and a rating columns.

    class Post < ActiveRecord::Base
      has_many :ratings
    end
    
    class Rating < ActiveRecord::Base
      has_many :posts
      has_many :users
    end
    

    Then you`ll be able to fetch all rating for the appropriate Post, the Post`s rating for the appropriate user and so on.

    You can even create a polymorphic relation to provide ratings functionality for other models:

    class Post < ActiveRecord::Base
      has_many :ratings, as: :rateable
    end
    
    class Rating < ActiveRecord::Base
      has_many :rateable, polymorphic: true
      has_many :users
    end