开发者

RoR 3.1 - Loading associated objects when querying child with a where phrase

开发者 https://www.devze.com 2023-04-09 04:29 出处:网络
I have the following structure class List < ActiveRecord::Base has_many :global_lists end class GlobalList < ActiveRecord::Base

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号