我收到一條錯誤undefined method 'answers'
此:@survey.questions.answers
Rails的:問題多層次的has_many和未定義的方法
只需運行@survey.questions
作品如你所期望。
這裏是我的模型設置:
class Survey < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:text].blank? }, :allow_destroy => true
end
class Question < ActiveRecord::Base
belongs_to :survey
has_many :answers
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:text].blank? }, :allow_destroy => true
end
class Answer < ActiveRecord::Base
belongs_to :question
has_many :responses
end
那麼,我究竟錯在這裏做什麼?每個模型都有正確的_id
字段來進行關聯。
我正在運行Rails 3.0.3。此外,這裏是完整的跟蹤:
>> @survey.questions.answers
NoMethodError: undefined method `answers' for #<Class:0x10375cc28>
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/association_collection.rb:443:in `send'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/association_collection.rb:443:in `method_missing'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/base.rb:1121:in `with_scope'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/association_proxy.rb:203:in `send'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/association_proxy.rb:203:in `with_scope'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/association_collection.rb:439:in `method_missing'
from (irb):9