1

我收到一个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
4

2 回答 2

0

@survey.questions是问题的集合。

尝试@survey.questions.first.answers

当然,在您看来,您可以这样做:

<% @survey.questions.each do |question| %>
  <%= question.title %>
  <% question.answers.each do |answer| %>
    <%= answer.title %>
  <% end %>
<% end %>
于 2011-02-04T18:37:47.697 回答
0
@survey.questions.map(&:answers)
于 2011-02-04T19:40:40.407 回答