質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

1回答

663閲覧

Railsで複数モデルを編集し、中間モデルにデータを保存したい

o.hiro

総合スコア7

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

1クリップ

投稿2018/04/03 10:47

編集2018/04/03 14:08

前提・実現したいこと

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を使用しています。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

h_daido

2018/04/03 13:55

"親となるモデルを保存した"時に呼ばれるcontrollerのメソッドの記載が無いようにおもうのですが、そこを追記してもらえないですか?
guest

回答1

0

ちょっと推測になってしまうのですが。

案A.
今はテンプレートのループが product > ingredients > product_ingredientsとループしていると思うんですが、普通は product > product_ingredients > ingredientsとするケースのほうが多いとおもうんですよね。なので、それに変えてみるのがオススメです。(おそらく今後の拡張もこのスタイルのほうがやりやすいことが多いと思います。)

案B.
accepts_nested_attributes_for :product_ingredients, allow_destroy: true
をIngredientモデルにも追加してみてください。
もしかするとこれだけで解消するかも。

投稿2018/04/03 14:28

h_daido

総合スコア824

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

o.hiro

2018/04/03 16:23

回答ありがとうございます! 今後のことも考えてループの順を逆にしてもう一度試してみます。
h_daido

2018/04/04 01:24

product_paramsの順番も変更する必要があると思いますので、お気をつけください;)
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問