2016-09-19 92 views
0

我有一個場景,我的應用程序與三個模型稱爲用戶,問題和答案交互。我從管理面板或通過導軌控制檯爲用戶添加了三個問題。現在在單獨的行動中,我需要顯示特定用戶的所有問題,並提供將多個答案添加爲每個答案的選項。我不知道如何繼續下去。這是我試過的示例代碼。軌道上的紅寶石多嵌套窗體

class User 
    has_many :questions 
    accepts_nested_attributes_for :questions 
    end 

    class Question 
    belongs_to :user 
    has_many :answers 
    accepts_nested_attributes_for :answers 
    end 

    class Answer 
     belongs_to :question 
    end 

    users_controller.rb 
    class UserController 
    def display_questions 
     @user = current_user 
    end 
    end 

    views/display_questions.html.erb 
    <%= form_for @user do |f| %> 
     <%= f.fields_for :questions do |q| %> 
     <%= q.fields_for :answers do |a| %> 
      <%= a.text_field :name %> 
     <% end %> 
     <%= q.link_to_add 'Add', :answers %> 
     <% end %> 
    <% end %> 

我得到該用戶的所有問題,但無法爲個別問題添加答案。我很困惑如何構建這些場景的嵌套字段,任何幫助表示讚賞。由於

回答

0

如果使用nested_form寶石它很容易,只是做:

<%= nested_form_for @user do |f| %> 
    <%= f.fields_for :questions do |q| %> 
     <%= q.fields_for :answers do |a| %> 
      <%= a.text_field :name %> 
     <% end %> 
     <%= q.link_to_add 'Add', :answers %> 
    <% end %> 
<% end %> 

注意nested_form_for,而不是的form_for

而且,你將需要添加屬性accepts_nested_attributes_for爲相應型號:

class User < ActiveRecord::Base 
    has_many :questions 
    accepts_nested_attributes_for :questions 
end 

class Question < ActiveRecord::Base 
    belongs_to :user 
    has_many :answers 
    accepts_nested_attributes_for :answers 
end 

class Answer < ActiveRecord::Base 
    belongs_to :question 
end 
+0

我試過了,但是它顯示出我無效的關聯。請確保accep_nested_attributes_for用於:answers關聯。 –

+0

編輯答案補充說。 –