前提・実現したいこと
accepts_nested_attributes_forを使って親子モデルを
まとめて登録したいと考えております。
model
question.rb (親モデル)
ruby
1class Question < ApplicationRecord 2 3 ... 4 has_many :answers 5 accepts_nested_attributes_for :answers 6end
answer.rb(子モデル)
class Answer < ApplicationRecord belongs_to :question ... end
###migrate
question.rb
class CreateQuestions < ActiveRecord::Migration[5.1] def change create_table :questions do |t| t.integer :user_id t.integer :answer_id t.string :title, limit: 32, null: false t.text :body, limit: 5000, null: false t.date :expire_date t.timestamps end end end
answer.rb
class CreateAnswers < ActiveRecord::Migration[5.1] def change create_table :answers do |t| t.integer :question_id t.string :answer, limit: 250, null: false t.boolean :other t.timestamps end end end
###view
new.html
<h2>投票作成</h2> <%= render 'form', question: @question %>
_form.html.erb
<%= form_for(question) do |f| %> <div class="field"> <%= f.label :title %><br /> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :body %><br /> <%= f.text_area :body %> </div> <%= f.fields_for :answers do |af| %> <div class="field"> <%= af.label :answer %><br /> <%= af.text_field :answer %> </div> <%= af.hidden_field :other, value: "false" %> <% end %> <div class="field"> <%= f.label :expire_date %><br /> <%= f.date_field :expire_date %> </div> <%= f.hidden_field :user_id, value: current_user.id %> <div class="actions"> <%= f.submit %> </div> <% end %>
###controller
questions_controller.rb
... def new @question = Question.new @question.answers.build end def create @question = Question.new(question_params) if @question.save redirect_to @question, notice: "作成しました。" else render :new end end # StrongParameters def question_params params.require(:question).permit(:user_id, :title, :body, :expire_date, answers_attributes: [:answer, :other]) end ...
解決したい問題
上記ソースによって登録処理を行うと
questionテーブルのanswer_idのみ値が反映されません。
その他のカラム(answerテーブル含む)は全て値が反映されます。
ご教授いただけると幸いです。
※question一つに対して、answerは複数登録できるように修正する予定ですがaccepts_nested_attributes_foを試験的に確認するためにanswerは一つにしております。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/13 13:01