Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Attributes of "joined" databases not showing up when using iterators?


  • Please log in to reply
No replies to this topic

#1 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 04 September 2013 - 02:10 AM

So I have this

class User < ActiveRecord::Base
  has_many :friends,    dependent: :destroy

and this

class Friend < ActiveRecord::Base
   belongs_to :user  ,  foreign_key: "friend_id" 
end

In Rails console, I do this

> user=User.find(24)
User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 24]]

It works fine. 

 

The association also works fine. 

> user.friends
  Friend Load (0.2ms)  SELECT "friends".* FROM "friends" WHERE "friends"."user_id" = $1  [["user_id", 24]]
 => #<ActiveRecord::Associations::CollectionProxy [#<Friend id: 1, user_id: 24, friend_id: 25, created_at: nil, updated_at: nil>, #<Friend id: 2, user_id: 24, friend_id: 26, created_at: nil, updated_at: nil>]>

My foreign key is "friend_id" in the Friends database/model. 

And this gives the correct answer too. 

> user.friends.first.user
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1  [["id", 25]]

I can access the friend's user attribute just fine, example: 

> user.friends.first.user.email
 => "johndoe@example.net"

So everything is honkey-dory working great. 

 

Then I do this.... 

> user.friends.each do |f|
>     f.user.email
>   end

and instead I get nothing.  I'm expecting to see all friend's email addresses, but all I get in console is just the Friends database listing, not linked to the user model. 

  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1  [["id", 26]]
 => [#<Friend id: 1, user_id: 24, friend_id: 25, created_at: nil, updated_at: nil>, #<Friend id: 2, user_id: 24, friend_id: 26, created_at: nil, updated_at: nil>]

And that's my question.... how come "email" didn't show up....

 

==================================================================================

 

UPDATE: It's amazing that when you write out your problem, the solution jumps out on you. 

Well i'll be damned... I didn't use the "puts" command, that's why the output didn't show :)  <embarrased!!!!> 

 

This works... oops :)

> user.friends.each do |f|
>     puts f.user.email
>   end
johndoe@example.net
mary@example.net

Nothing to see here, move along now :)


  • james likes this




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users