2011-02-04 1 views
1

Я получаю ошибку undefined method 'answers' с этим: @survey.questions.answersRails: Проблема с 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 

ответ

0

@survey.questions представляет собой набор вопросов.

@survey.questions.first.answers попробовать

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

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