前提・実現したいこと
Railsで複数モデルに対応したフォームを作成しています。
親となるモデルを保存した際に、中間モデルに外部キー以外の値(:unit, :amount)を保存、もう片方のモデルにも値(:name)を保存させたいです。
具体的には、商品Aの情報を更新するページには、成分に関する動的なフォームがあり、「成分BをXグラム」と入力する欄があります。
発生している問題・エラーメッセージ
こちらの記事を参考に、モデルを編集する際、多対多のもう片方のモデルに同時に保存することはできました。(成分名の保存)
https://learn.co/lessons/has-many-through-forms-rails
しかし、中間モデルに値を保存することができない状況です。(分量、単位の保存)
該当のソースコード
モデル
ruby
1# 商品モデル 2class Product < ApplicationRecord 3 4has_many :product_ingredients, dependent: :destroy 5has_many :ingredients, through: :product_ingredients 6accepts_nested_attributes_for :product_ingredients, allow_destroy: true 7accepts_nested_attributes_for :ingredients 8 9def ingredients_attributes=(ingredient_attributes) 10 ingredient_attributes.values.each do |ingredient_attribute| 11 ingredient = Ingredient.find_or_create_by(ingredient_attribute) 12 self.ingredients << ingredient 13 end 14end 15end 16 17 18# 成分モデル 19class Ingredient < ApplicationRecord 20 has_many :product_ingredients, dependent: :destroy 21 has_many :products, through: :product_ingredients 22end 23 24 25# 中間モデル 26class ProductIngredient < ApplicationRecord 27 belongs_to :product 28 belongs_to :ingredient 29end
products_controller.rb
def new @product = Product.new end def create @product = Product.new(product_params) if @product.save redirect_to setting_detail_product_path(@product), notice:"新しい商品を作成・保存しました。" else render 'new', notice:"保存に失敗しました。" end end def detail @product = Product.find(params[:id]) end def update @product = Product.find(params[:id]) if @product.update(product_params) redirect_back(fallback_location: setting_detail_product_path(@product), notice: "更新できました") end end private def product_params params.require(:product).permit( ingredients_attributes:[ :name, product_ingredients_attributes:[:id, :unit, :amount] ] ) end
detail.html.erb
ruby
1 <div class="text-right"> 2 <%= f.fields_for :ingredients, @product.ingredients.build do |ingredients_fields| %> 3 <%= link_to_add_association '成分を追加', f, :ingredients, 4 data: { 5 association_insertion_node: '#detail-association-insertion-point', 6 association_insertion_method: 'append' } 7 %> 8 </div> 9 <table class="table table-list"> 10 <thead> 11 <tr> 12 <th>成分</th> 13 <th>数量</th> 14 <th>単位</th> 15 <th></th> 16 </tr> 17 </thead> 18 <tbody id="detail-association-insertion-point"> 19 <div class="form-group"> 20 <%= render "ingredient_fields", f:ingredients_fields %> 21 <% end %> 22 </div> 23 </tbody> 24 </table>
_ingredient_fields.html.erb
ruby
1<tr class="nested-fields"> 2 <td><%= f.text_field :name %></td> 3 <%= f.fields_for :product_ingredients, @product.product_ingredients.build do |pi| %> 4 <td><%= pi.text_field :amount %></td> 5 <td><%= pi.select :unit, [["mg","mg"],["g","g"],["μg","μg"]] %></td> 6 <% end %> 7 <td><%= link_to_remove_association "削除", f %></td> 8</tr>
色々と調べて試行錯誤してみてもこのような場合どうすればいいかわかりませんでした。
解決方法をご存知の方がいらっしゃればアドバイスいただけると大変嬉しいです。
よろしくお願いいたします。
補足情報(FW/ツールのバージョンなど)
動的フォームに関してはcocoonを使用しています。