Reputation: 3624
The user clicks a button to upvote an Item. This should update @item.upvotes.
Where does this go? Here are the options I thought of. I'm not extremely familiar with the correct compartmentalization and I'm hoping to learn the reasoning behind this too.
Upvotes: 2
Views: 854
Reputation: 10918
The correct way is to have the upvote button (view) call a controller by routing to the correct method. Inside the controller method you tell the model to update the field. This is the MVC principle.
A model in Rails usually just holds validations, relations and the like. Updating a field is clearly a job for the controller.
I'm not that fluent with my ruby any more as I'm using java now but the controller should probably look something like this:
class ItemsController
def upvote
Items.increment_counter(:upvote, params[:id])
end
In the view you have a button somewhere (via form or link_to) that posts the id to say a "/upvote" action:
<%= link_to "upvote", upvote_path(:id => @item.id) %>
In your routes file you send that to Items#upvote.
match "/upvote" => "items#upvote"
Upvotes: 3
Reputation: 13388
Check counter cache:
http://railscasts.com/episodes/23-counter-cache-column
Upvotes: -2