Rails:多级has_many和undefined方法的问题

时间:2011-02-04 18:33:55

标签: ruby-on-rails has-many belongs-to

我收到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

2 个答案:

答案 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)