我收到undefined method 'answers'
错误@survey.questions.answers
只需按照您的预期运行@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
答案 0 :(得分:0)
@survey.questions
是一系列问题。
尝试@survey.questions.first.answers
当然,在您看来,您可以这样做:
<% @survey.questions.each do |question| %>
<%= question.title %>
<% question.answers.each do |answer| %>
<%= answer.title %>
<% end %>
<% end %>
答案 1 :(得分:0)
@survey.questions.map(&:answers)