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:infind_from_ids' from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/ active_record/base.rb:504:in
find’
from /usr/lib/ruby/gems/1.8/gems/utility_belt-1.0.6/lib/
rails_finder_shortcut.rb:12:insend' from /usr/lib/ruby/gems/1.8/gems/utility_belt-1.0.6/lib/ 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