views:

41

answers:

1

Hi,

I'm having trouble with getting a named scope working using using an attribute of the associated model other than the id column.

I have a Firm model which has a city_id column. I also have a City model with a name column.

I want to get restful urls like this so as to make use of the has_scope gem and have skinny controllers

http://localhost:3000/firms?by_city=Dublin

However using the present code I can only insert the city Id

http://localhost:3000/firms?by_city=546

Here is my named_route

class Firm < ActiveRecord::Base       
named_scope :by_city, proc {|city| { :conditions => { :city => city } } }
end

Any ideas about how to modify the named scope so as to generate urls using the name would be greatly appreciated!

Thanks,

Jack

+2  A: 

You'll need to add belongs_to to the Firm class and then for the named scope add a join on city so you can get to the city's name in the query. Something like this

class Firm < ActiveRecord::Base
  belongs_to :city
  named_scope :by_city, lambda {|city_name| {:joins => :city, :conditions => {:city => {:name => city_name}}}}
end
Corey
Thanks - this works but requires a slight modification named_scope :by_city, lambda {|city_name| {:joins => :city, :conditions => {:cities => {:name => city_name}}}}
Jack Kinsella