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 に答える