Apparently I assumed functionality that doesn’t exist for this
association. Should I not be able to reference the target model as an
attribute?
Here are my models:
class User < ActiveRecord::Base
has_one :membership
has_one :role, :through => :membership
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Role < ActiveRecord::Base
end
But, the “role” attribute for an instance of User always contains nil:
user = User.new
=> #<User id: nil, created_at: nil, updated_at: nil>user.save!
=> truemembership = user.create_membership
=> #<Membership id: 1, user_id: 1, role_id: nil, created_at:
“2009-05-20 05:40:1
7”, updated_at: “2009-05-20 05:40:17”>role = membership.create_role
=> #<Role id: 1, created_at: “2009-05-20 05:40:33”, updated_at:
“2009-05-20 05:4
0:33”>user.membership
=> #<Membership id: 1, user_id: 1, role_id: 1, created_at: “2009-05-20
05:40:17”
, updated_at: “2009-05-20 05:40:17”>user.membership.role
=> #<Role id: 1, created_at: “2009-05-20 05:40:33”, updated_at:
“2009-05-20 05:4
0:33”>user.role
=> nilquit
Why does user.membership.role contain a record, but user.role does not?