Rails: проблема с многоуровневым has_many и неопределенным методом - PullRequest
1 голос
/ 04 февраля 2011

Я получаю 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 голосов
/ 04 февраля 2011
@survey.questions.map(&:answers)
0 голосов
/ 04 февраля 2011

@survey.questions - это сборник вопросов.

попробуй @survey.questions.first.answers

Конечно, на ваш взгляд, вы можете сделать:

<% @survey.questions.each do |question| %>
  <%= question.title %>
  <% question.answers.each do |answer| %>
    <%= answer.title %>
  <% end %>
<% end %>
...