2012-02-22 16 views
0

基本要點: 我目前正在嘗試創建具有向上或向下功能的計數器計數器。我創建了一個單獨的模型來顯示評分計數器和計數器屬於該帖子。我試圖創造一些沿着Reddit或甚至Stackoverflow的東西。我目前堅持要做什麼。謝謝大家。Rails:A向上或向下計數器第二部分

DB:評分表:POST_ID,USER_ID,評級

DB:郵政表:RATINGS_COUNT

評級模型的

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

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

郵政型號

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

    validates :user_id, presence: true 
    validates :smiles, presence: true 
end 

評級控制器

Nothing in it 

柱控制器

class PostsController < ApplicationController 

    def rate 
    @post = post.find(params[:id]) 
    if params[:ratings_count] 
     @[email protected]_count+1 
    end 
    end 

    def unrate 

    unsure 

    end 
end 

評級表

<%=form_for @post, :action=>"rate" do |f|%> 
<%= f.hidden_field :ratings_count %> 
<%=f.submit "Rate"%> 
<%end%> 
+0

潛在相關閱讀:http://www.evanmiller.org/how-not-to-sort-by-average-rating.html – sarnold 2012-02-22 02:53:44

回答

0

你可以使用這樣的事情: http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000348

class PostsController < ApplicationController 

    def rate 
    Post.increment_counter(:ratings_count, params[:id]) if params[:ratings_count] 
    end 

    def unrate 
    # You will obviously need to check for a ratings_down or something similar field in your form 
    Post.decrement_counter(:ratings_count, params[:id]) if params[:ratings_count] 
    end 
end 
+0

我不確定是否我正確設置了表單?你能證實嗎?並感謝您 – Kellogs 2012-02-22 03:01:32

+0

您是否收到任何錯誤? – dennismonsewicz 2012-02-22 03:09:32

+0

不,它只是不增加 – Kellogs 2012-02-22 03:13:03