Kellogs
Kellogs

Reputation: 471

Ajax/Increment Counter voting methods in Ruby on Rails

I am unsure of what I am doing wrong, very confused. I am trying to make a rating counter like the old Digg.com rating counter. Can anyone take a look at my code and help me out?

Things to note is that here are the separate database tables/models: Rate, Post, User

Rate: user_id integer, post_id integer and ratings_count integer default => 0

Post: ratings_count integer default => 0

This is what I am currently working with, all the code that I have for this rating system, if it is not shown then I don't have it and thus missing and would love if someone can help point out what is missing. Thank you.

Rate Controller

class RateController < ApplicationController
  def create
    @post.increment_counter(:ratings_count, params[:id]) if params[:ratings_count]
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end

  def increment_counter(counter_name, id)
    update_counters(:post, :ratings_count => 1)
  end
end

Rate Model

class Rate < ActiveRecord::Base
  attr_accessible :post_id, :user_id, :ratings_count
  has_many :posts
  has_many :users

  validates :post_id, presence: true
  validates :user_id, presence: true

end

Rate Form

<%=form_for @rate do |f|%>
<%= f.hidden_field :ratings_count %>
<%=f.submit "Rate"%>
<%end%>

Micropost Model

class Micropost < ActiveRecord::Base
  attr_accessible :ratings_count
  belongs_to :user
  has_many :ratings

  validates :ratings, presence: true
end

create.js.erb for rate

$("#rates").html("Rates: <%= @micropost.ratings_count.count %>")

Upvotes: 0

Views: 719

Answers (1)

Said Kaldybaev
Said Kaldybaev

Reputation: 10002

check out the thumbs_up gem. with this gem you just need to include this to your model:

  • acts_as_voteable

and add some logic to your controller

Upvotes: 2

Related Questions