timpone
timpone

Reputation: 19969

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

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

Upvotes: 1

Views: 126

Answers (3)

Jordan Running
Jordan Running

Reputation: 106027

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

Upvotes: 2

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

GlobalList.find_by_global_id(23).list

Upvotes: 0

rdvdijk
rdvdijk

Reputation: 4398

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

Upvotes: 1

Related Questions