I have the following relationships that work in the rails console but not when I run the site what I am doing wrong?
class C 开发者_StackOverflow中文版< ActiveRecord::Base
belongs_to :b
end
class B < ActiveRecord::Base
belongs_to :a
has_many :c
def title
a.title
end
end
Table C has a foreign key to B and B has a foreign key to A.
This works in the rails console.
c = C.find(12)
c.b.title
But it doesn't work when I run the site.
Here is the error I get
NoMethodError (undefined method `title' for #<ActiveRecord::Associations::BelongsToAssociation:0x104feb5a0>):
Rather than defining a method to do this, delegate
! In app/models/c.rb
:
delegate :title, :to => :b
And then in app/models/b.rb
:
delegate :title, :to => :a
has_one(association_id, options = {}) Specifies a one-to-one association with another class. This method should only be used if the other class contains the foreign key. If the current class contains the foreign key, then you should use belongs_to instead. See also ActiveRecord::Associations::ClassMethods’s overview on when to use has_one and when to use belongs_to.
I had to turn the class B title method into a class method to get it to work.
精彩评论