how do i access attriutes when using eager_load has_many

15 views
Skip to first unread message

tom

unread,
Jan 27, 2016, 12:50:12 PM1/27/16
to Ruby on Rails: Talk
Hi
this code:

  x = Project.where('status=?','active').eager_load(:tasks)


produces a nice query, in sql everythig is ok, all columns have been alias as t0_r1,....


but how do i access it? my loops are failing when tryin to access the associates attribute:

  x = Project.where('status=?','active').eager_load(:tasks)
     x.each do |rec|
      p rec.id #<< OK
      p rec.tasks.id # << OUCH
    end


pls advise

thx



Hassan Schroeder

unread,
Jan 27, 2016, 1:06:47 PM1/27/16
to rubyonrails-talk
On Wed, Jan 27, 2016 at 9:49 AM, tom <toma...@gmail.com> wrote:

> x = Project.where('status=?','active').eager_load(:tasks)

> but how do i access it? my loops are failing when tryin to access the
> associates attribute:
>
> x = Project.where('status=?','active').eager_load(:tasks)
> x.each do |rec|
> p rec.id #<< OK
> p rec.tasks.id # << OUCH
> end

> pls advise

1. "OUCH"? What does that mean? You'll generally get more useful
answers if you show an actual error message. And for that matter
googling that error will frequently give you pointers towards solving
it yourself.

2. I would *guess* that "tasks" is a collection; do you expect that to
have an id? Or are you looking for the id of an individual task?

If in doubt, try: p rec.tasks.class

--
Hassan Schroeder ------------------------ hassan.s...@gmail.com
http://about.me/hassanschroeder
twitter: @hassan
Consulting Availability : Silicon Valley or remote

tom

unread,
Jan 27, 2016, 1:10:03 PM1/27/16
to Ruby on Rails: Talk
ok, u r right - i was just frustrated because i was going back and forth between joins , includes etc - here the 'error'

undefined method `id' for #<Task::ActiveRecord_Associations_CollectionProxy:0xc4686a4>



--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CACmC4yDjCt977YQ8zEQE0jEe3wrWN1mhUmxuujBFuSGSo6qXww%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

tom

unread,
Jan 27, 2016, 1:44:22 PM1/27/16
to Ruby on Rails: Talk
ok, if i do this then i can acces the associated records:
x = Project.where('status=?','active').eager_load(:tasks)
     x.each do |rec|
      p rec.id #<< OK
      rec.tasks each do |y|
      p y.id
      end
    end


i guess i was just expecting a flat table because thats what i saw in the mysql query result pane

thx again

Reply all
Reply to author
Forward
0 new messages