Roy
Roy

Reputation: 3624

Where does an upvote method belong in Rails?

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.

  1. Model -- as an instance method that updates immediately
  2. Controller -- as a method that gets called using routing. If this is the case, why do we do this instead of making an instance method on the model?
  3. Helper -- I'm not too familiar with what these do, but I know they can be called from the view. However, they seem to be better for things like string manipulation or working with stuff that belongs in the view.

Upvotes: 2

Views: 854

Answers (2)

Pete
Pete

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

Victor
Victor

Reputation: 13388

Check counter cache:

http://railscasts.com/episodes/23-counter-cache-column

Upvotes: -2

Related Questions