Rails: Issue with multi-level has_many and undefined method
I'm getting an undefined method 'answers'
error with this: @survey.questions.answers
Just running @survey.questions
works as you'd expect.开发者_JS百科
Here's my model setup:
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
So, what am I doing wrong here? Each model has the correct _id
field to make the association.
I'm running Rails 3.0.3. Also, here's the full trace:
>> @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
@survey.questions
is a collection of questions.
try @survey.questions.first.answers
Of course, in your view, you could do:
<% @survey.questions.each do |question| %>
<%= question.title %>
<% question.answers.each do |answer| %>
<%= answer.title %>
<% end %>
<% end %>
@survey.questions.map(&:answers)
精彩评论