fields_forで、一度に複数のテーブルに保存したいと考えています。フォーム内の各入力項目はブラウザ上で確認できる状態ですし、ページ遷移時にエラーも起こりません。ただ、子のテーブルにデータが保存されません。(fields_forの部分がUnpermitted parameterとなってしまうのが問題なのかなと思っています)
ネットで調べたところ、Rails5では、optional: trueやinverse_of: :profileをモデル内に記載した時に、問題解決したとの投稿を見かけましたが、私の場合、解決に至りませんでした。下記が関連するところのコードとなります。ご意見いただけますと幸いです。
profile.rb
ruby
1class Profile < ApplicationRecord 2 has_many :languages , inverse_of: :profile 3 accepts_nested_attributes_for :languages, allow_destroy: true 4end
language.rb
ruby
1class Language < ApplicationRecord 2 belongs_to :profile, optional: true, required:true 3end
_form.htmk.erb :profile本体のcontactまではデータ保存がかなっています。language部分が表示だけで、保存が叶いません。
ruby
1<div class="field"> 2 <%= f.label :contact %> 3 <%= f.text_field :contact %> 4 </div> 5 6 <%= f.fields_for :language do |i| %> 7 <div class="field"> 8 <%= i.label :language %> 9 <%= i.text_field :language %> 10 </div> 11 <div class="field"> 12 <%= i.label :rank %> 13 <%= i.text_field :rank %> 14 </div> 15 <% end %>
profiles_controller.rb
ruby
1 def new 2 @profile = Profile.new 3 @profile.languages.build 4 end 5 6 def edit 7 end 8 9 def create 10 @profile = Profile.new(profile_params) 11 @profile.id = @current_user.id 12 ...... 13 14 ...... 15 def profile_params 16 params.require(:profile).permit(..., :contact, languages_attributes: [:id,:language,:rank]) 17 end
※試しに上記の一部を”language_attributes”に変えてみましたがうまくいきませんでした。
ターミナルのログの一部
"contact"=>"f", "language"=>{"language"=>"g", "rank"=>"11"}}, "commit"=>"Submit"}
Unpermitted parameter: language
画像
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。