###前提・実現したいこと
以下のハッシュ内のquestion_idとrateのバリューをそれぞれ保存したいです。indexの個数が決まっておらず複数個になりうるためindex0,index1,index2などをカラムに追加することができません。どのように実装すればよいでしょうか。
id | rate | question_id | child_id
1 | 1 | 159 | 509
2 | 2 | 160 | 509
3 | 1 | 161 | 509
このように保存したいと思ってます。
###発生している問題・エラーメッセージ
Started POST "/children/509/answers" Processing by AnswersController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"略", "answer"=>{"index0"=>{"question_id"=>"159", "rate"=>"1"}, "index1"=>{"question_id"=>"160", "rate"=>"2"}, "index2"=>{"question_id"=>"161", "rate"=>"1"}}, "commit"=>"SEND", "child_id"=>"509"} Unpermitted parameters: index0, index1, index2 (0.2ms) BEGIN SQL (0.5ms) INSERT INTO `answers` (`child_id`, `created_at`, `updated_at`) VALUES (509, '2017-08-08 19:13:31', '2017-08-08 19:13:31') (1.4ms) COMMIT Unpermitted parameters: index0, index1, index2 (0.1ms) BEGIN SQL (0.2ms) INSERT INTO `answers` (`child_id`, `created_at`, `updated_at`) VALUES (509, '2017-08-08 19:13:31', '2017-08-08 19:13:31') (0.4ms) COMMIT Unpermitted parameters: index0, index1, index2 (0.2ms) BEGIN SQL (0.8ms) INSERT INTO `answers` (`child_id`, `created_at`, `updated_at`) VALUES (509, '2017-08-08 19:13:31', '2017-08-08 19:13:31') (0.3ms) COMMIT Child Load (0.2ms) SELECT `children`.* FROM `children` WHERE `children`.`id` = 509 LIMIT 1
###該当のソースコード
Ruby
1<%= form_for [@child, @answer] do |f| %> 2<% @parent.questions.each_with_index do |question, i| %> 3<p>(Q<%= i + 1 %>) <%= question.text %> 4<%= f.hidden_field :question_id, :value => question.id, :index => "index#{i}" %> 5 <label><%= f.radio_button :rate, 0, :index => "index#{i}" %>A</label> 6 <label><%= f.radio_button :rate, 1, :index => "index#{i}" %>B</label> 7 <label><%= f.radio_button :rate, 2, :index => "index#{i}" %>C</label> 8 <label><%= f.radio_button :rate, 3, :index => "index#{i}" %>D</label> 9 </p> 10<% end %> 11<%= f.submit "SEND" %> 12<% end %>
Ruby
1class AnswersController < ApplicationController 2 3 def new 4 @child = Child.find(params[:child_id]) 5 @parent = @child.parent 6 @answer = Answer.new 7 end 8 9 def create 10 hash = params[:answer] 11 ary = [] 12 hash.each_key do |key| 13 ary << key 14 end 15 ary.each do |key_a| 16 Answer.class_eval { attr_accessor :"#{key_a}" } 17 Answer.create(create_params(key_a)) 18 end 19 @child = Child.find(params[:child_id]) 20 end 21 22 private 23 def create_params(key_a) 24 params.require(:answer).permit(:key_a => [:question_id, :rate]).merge(child_id: params[:child_id]) 25 end 26end
Ruby
1class Answer < ActiveRecord::Base 2 belongs_to :child 3 belongs_to :question 4end 5
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/08 22:58
2017/08/08 23:10