Quick Question

I have this method in a controller

def sort_by_cuisine
#@restaurants = Restaurant.find(:all, :conditions => [“cuisine_id =
:id”, params], :order => params[:sort])
@cuisines = Cuisine.find_all

And I want to put the bulk of it in the model, but still call it from
the controller. How can I do this? I’m fairly new to Ruby on Rails and
I’ve tried using local variables but this isn’t working. Thanks.

Richard wrote:

I’ve tried using local variables but this isn’t working. Thanks.

Assuming Cuisine has_many :restaurants and Restaurant belongs_to
:cuisine (this is what I’m reading into the cuisine_id in Restaurant),
you could simply rewrite this:

def sort_by_cuisine
@cuisine = Cuisine.find(params[:id]) # which will provide you with an
instance variable, cuisine, through which you can access the details of
that cuisine in the view, for the title, for example. This line will
throw an error if someone tries to supply an id that’s not valid –
which is a good thing, I think
@restaurants = @cuisine.restaurants.find(:all, :order =>
params[:sort]) # assuming params[:sort] provides an SQL fragment, e.g.
“updated_at DESC”
@cuisines = Cuisine.find(:all) # you can use find_all, but it’s

You could of course make a #sorted_find_all method in the Restaurant
model, but I’m not sure it’s worth it in this case. The ‘:conditions =>
[“cuisine_id =
:id”’ is already in the models, thanks to the magic of has_many and


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs