rails初心者です。Teacher登録確認画面を作っています。確認画面の時にhidden_fieldを用いているのですが、place_idsなどの中間テーブルを使った値が使えず、 validates :place_ids, presence: trueに引っかかり、Teacherを保存することができません。どのようにすればよろしいでしょうか。
確認画面のconfirm.html.erbです
<%= form_for(@teacher) do |f| %> <div class="field"> <%= f.fields_for :places do |place_f| %> <%= f.label :"指導場所" %> <%= place_f.hidden_field :id %> <p><%= place_f.object.name %></p> <% end %> </div> <%= f.submit '投稿画面に戻る', name: 'back' %> <%= f.submit '投稿する' %> <% end %>
登録画面のnew.html.erbです
<%= form_for(@teacher, url: {action: 'confirm'} ) do |f| %> <div class ="field"> <%= f.label :"指導場所" %> <%= f.collection_check_boxes :place_ids, @place, :id, :name ,{include_hidden: false},{multiple: true} %> </div> <%= f.submit "確認画面へ" %> <% end %>
teacher.rbです
class Teacher < ApplicationRecord has_many :teachers_places, foreign_key: 'teacher_id', dependent: :destroy has_many :places, through: :teachers_places, dependent: :destroy accepts_nested_attributes_for :places validates :place_ids, presence: true end
teacher_controller.rbのnewアクションとconrilmアクションとcreateアクションとStrong Parametersです
class TeachersController < ApplicationController def new @teacher = Teacher.new @place = Place.all @teacher.teachers_places.build end def confirm @place = Place.all @teacher = Teacher.new(teacher_params) if @teacher.valid? render 'confirm' else render 'new' end end def create @place = Place.all @teacher = Teacher.new(teacher_params) @teacher.place_ids = params[:teacher][:places_attributes] if params[:back] render 'new' elsif @teacher.save redirect_to teachers_url else render 'new' end end private def teacher_params params.require(:teacher).permit(places_attributes: [:id], place_ids:[]) end end
アクションに渡っているparamsの内容
confirm
"teacher"=>{"place_ids"=>["3", "4"]}
create
"teacher"=>{"places_attributes"=>{"0"=>{"id"=>"3"}, "1"=>{"id"=>"4"}}}
rails cでのplack(:id)の結果
irb(main):003:0> Place.pluck(:id) (0.4ms) SELECT "places"."id" FROM "places" => [1, 2, 3, 4]
質問がわかりにくく申し訳ありません。ご回答のほどよろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。