Association chaining

Hello,

I am trying to setup some basic association chaining. I have the
following models:

class User < ActiveRecord::Base
has_many :posts
end

class Post < ActiveRecord::Base
has_many :tags
belongs_to :user
end

class Tag < ActiveRecord::Base
belongs_to :post
end

I made some basic migrations and created the database tables.
Then I start script/console and start creating some data:

Loading development environment (Rails 2.0.2)

User.create
=> #<User id: 1, created_at: “2008-01-10 15:16:06”, updated_at:
“2008-01-10 15:16:06”>

Post.create(:user_id => 1)
=> #<Post id: 1, user_id: 1, created_at: “2008-01-10 15:16:16”,
updated_at: “2008-01-10 15:16:16”>

Tag.create(:post_id => 1)
=> #<Tag id: 1, post_id: 1, created_at: “2008-01-10 15:16:27”,
updated_at: “2008-01-10 15:16:27”>

So far so good. But now I want to test the associations.

First find a tag:

Tag.find(:first)
=> #<Tag id: 1, post_id: 1, created_at: “2008-01-10 15:16:27”,
updated_at: “2008-01-10 15:16:27”>

Then find the associated post:

Tag.find(:first).post
=> #<Post id: 1, user_id: 1, created_at: “2008-01-10 15:16:16”,
updated_at: “2008-01-10 15:16:16”>

Still fine, but it breaks if I want to chain the association further:

Tag.find(:first).post.user
ActiveRecord::RecordNotFound: Couldn’t find User without an ID
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/
active_record/base.rb:1248:in find_from_ids' from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/ active_record/base.rb:504:infind’
from /usr/lib/ruby/gems/1.8/gems/utility_belt-1.0.6/lib/
rails_finder_shortcut.rb:12:in send' from /usr/lib/ruby/gems/1.8/gems/utility_belt-1.0.6/lib/ rails_finder_shortcut.rb:12:inuser’
from (irb):6

I tried different models, rails versions, but can not find what I am
doing wrong… Anyone?

Ren

I found my problem. It is within the utilitybelt gem I use for my irb
sessions. This apparently does not allow association chaining.

On 10 jan, 15:20, renek [email protected] wrote:

has_many :tags
Loading development environment (Rails 2.0.2)>> User.create
So far so good. But now I want to test the associations.

rails_finder_shortcut.rb:12:in `user’
from (irb):6

I tried different models, rails versions, but can not find what I am
doing wrong… Anyone?

René