Creating a scope in Rails 3 based on a has_one :through relationship -


rails 3.0.3 , ruby 1.9.2

i have following class

class item < activerecord::base   belongs_to :user   has_one :country, :through => :user    ..  end 

so itema.country yields "united states"

the question how created (named) scope items owned users

when try like:

scope :american, where('countries.name' => 'united states').includes([:user, :country]) 

then item.american keeps coming empty when item.first.country => 'united states'

incidentally, in rails 2.3.4 version had:

named_scope :american, :include => {:user, :country}, :conditions => { 'countries.printable_name' => 'united states' } 

and worked advertised.

you forgot pluralize table names, think ordering of include , may matter. it's recommended use join instead when specifying conditions on associations so:

scope :american, joins(:users, :countries).where('countries.name' => 'united states') 

if you'd prefer still use includes:

scope :american, includes(:users, :countries).where('countries.name' => 'united states') 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -