2016-09-19 19 views
0

私のアプリケーションは、User、Question and Answerという3つのモデルと対話するシナリオがあります。私は、管理者パネルまたはレールコンソールからユーザーのために3つの質問を追加しました。別のアクションでは、私は特定のユーザーのすべての質問を表示し、それぞれのテキストとして複数の回答を追加するオプションを提供する必要があります。私はさらに進める方法を知らない。ここで私が試した私のサンプルコードです。Ruby on Railsの複数ネストフォーム

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 %> 

をノート代わりにのform_for

nested_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

私はそれを試みましたが、私に無効な関連付けを示しています。accepts_nested_attributes_forが:answers associationに使用されていることを確認してください。 –

+0

これを追加する編集済みの回答。 –