2011-02-04 67 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 %> 
0
@survey.questions.map(&:answers) 
相關問題