RoR 3.1 - Loading associated objects when querying child with a where phrase
I have the following structure
class List < ActiveRecord::Base
has_many :global_lists
end
class GlobalList < ActiveRecord::Base
set_table_name :globals_lists
belongs_to :list
end
and the following:
gl=GlobalList.find(1) #works
gl.list #works
gm=GlobalList.where(:global_id => 23).includes(:list) #works
gm.list # doesn't work开发者_StackOverflow中文版
How do I access the list when using a where for returning the object?
thx
edit: is there a way for me to flatten this and get all the lists that have this? I guess I could iterate through but have the feeling there might be some syntax that I'm not aware of
The problem is that GlobalList.find
returns a single GlobalList object whereas your query with where
returns an ActiveRecord::Relation
object (which represents a whole set of objects). You want:
gm = GlobalList.where(:global_id => 23).includes(:list).first
This line:
gm = GlobalList.where(:global_id => 23).includes(:list)
returns a collection of models. You need to first the first to get the list.
gm.first.list
GlobalList.find_by_global_id(23).list
精彩评论