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

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

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

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

Ruby

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

Ruby on Rails

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

Q&A

0回答

699閲覧

accepts_nested_attributes_forを使った多対多モデルの重複保存を防ぎたい

o.hiro

総合スコア7

Ruby on Rails 5

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

Ruby

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

Ruby on Rails

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

0グッド

0クリップ

投稿2018/04/06 01:21

前提・実現したいこと

Productモデル(多)、Quantityモデル(中間)、Ingredientモデル(多)があります。

Productモデルを保存する際に、中間モデルとなるQuantityモデル、多対多のもう1方の多モデルである、Ingredientモデルへの同時保存をさせたいのですが、

その際、Ingredientモデルではすでにある名前(:name)の場合は新しく登録せず、ない場合のみ登録するというようなことをしたいと考えています。

現状

現在の状況としては、Productモデルを更新するフォームを作成し、中間モデルとなるQuantityモデル、多対多のもう1方の多モデルである、Ingredientモデルへの同時保存ができる状態です。

しかし、名前(:name)が重複しても保存できてしまう状態です。

自分でやったこと

調べてみてfind_or_create_byをどこかで使用するとわかったので、
https://learn.co/lessons/has-many-through-forms-rails のサイトのCREATE NEW CATEGORYの項目を参考に以下の内容をProduct.rbに記述しました。
しかし、名前が重複されて保存される状態は変わらないです。

Product.rb

ruby

1 def ingredient_attributes=(ingredient_attributes) 2 ingredient_attributes.values.each do |ingredient_attribute| 3 ingredient = Ingredient.find_or_create_by(ingredient_attribute) 4 Quantity.ingredient << ingredient 5 end 6 end

以下、作成したコードとなります。

該当するコード

product.rb

ruby

1class Product < ApplicationRecord 2 3 has_many :quantities 4 has_many :ingredients, through: :quantities 5 accepts_nested_attributes_for :quantities, reject_if: :all_blank, allow_destroy: true 6 accepts_nested_attributes_for :ingredients 7 8 def ingredient_attributes=(ingredient_attributes) 9 ingredient_attributes.values.each do |ingredient_attribute| 10 ingredient = Ingredient.find_or_create_by(ingredient_attribute) 11 Quantity.ingredient << ingredient 12 end 13 end 14 15end

quantity.rb

ruby

1class Quantity < ApplicationRecord 2 belongs_to :product 3 belongs_to :ingredient 4 accepts_nested_attributes_for :ingredient, reject_if: :all_blank 5 6end

ingredient.rb

ruby

1class Ingredient < ApplicationRecord 2 has_many :quantities 3 has_many :products, through: :quantities 4end

products_controller.rb

ruby

1 2 def detail 3 @product = Product.find(params[:id]) 4 @photo = Photo.new 5 end 6 7 def update 8 @product = Product.find(params[:id]) 9 if @product.update(product_params) 10 redirect_back(fallback_location: setting_detail_product_path(@product), notice: "更新できました") 11 end 12 end 13 14 private 15 16 def product_params 17 params.require(:product).permit( 18 quantities_attributes:[:id, :ingredient, :ingreident_id, :product_id, :unit, :amount, :_destroy, 19 ingredient_attributes:[:id, :_destroy, :ingreident_id, :name] 20 ] 21 ) 22 end

products/detail.html.erb

ruby

1<%= simple_form_for @product do |f| %> 2 <%= link_to_add_association 'add ingredient', f, :quantities, 3 'data-association-insertion-node' => "#product-ingredients ol", 'data-association-insertion-method' => "append", 4 :wrap_object => Proc.new {|quantity| quantity.build_ingredient; quantity } %> 5 <div id="product-ingredients"> 6 <ol> 7 <%= f.fields_for :quantities do |quantity| %> 8 <%= render 'quantity_fields', f: quantity %> 9 <% end %> 10 </ol> 11 </div> 12<% end %>

products/_quantity_fields.html.erb

ruby

1<li class="control-group nested-fields"> 2 <div class="controls"> 3 <%= f.label :amount, "Amount:" %> 4 <%= f.text_field :amount %> 5 6 <%= f.fields_for :ingredient do |quantity_ingredient| %> 7 <%= f.label :set_name, "name:" %> 8 <%= quantity_ingredient.text_field :name %> 9 <% end %> 10 11 <%= link_to_remove_association "remove", f %> 12 </div> 13</li>

解決方法をご存知の方がいらっしゃればアドバイスいただけると大変嬉しいです。
よろしくお願いいたします。

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

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

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

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問