Reputation: 689
I have simple rails application. Create, delete, edit posts. And I need to rate this posts. Where to place rate function, in model or controller? and why?
Upvotes: 2
Views: 136
Reputation: 211560
Usually this sort of thing plays out in both places. You'll have a rate
method on the model, and you'll have a rate
action in the controller.
Remember that it's the controller's primary function to receive requests, load the proper models, adjust them as necessary, and save the results. Often the models will implement the functionality required to facilitate this.
In the controller you'd make something like this:
class ItemsController < ApplicationController
def rate
@item.rate!(session[:user_id], params[:rating])
end
end
In the model you'd have something like this:
class Item < ActiveRecord::Base
has_many :ratings
def rate!(user_id, rating)
self.ratings.create(:user_id => user_id, :rating => rating)
end
end
Without a controller you can't access the models, it has to go through that layer, and without a model you have no persistent data. They work together.
Upvotes: 5