前提・実現したいこと
Railsで複数モデルに対応したフォームを作成しています。
親となるモデルを保存した際に、中間モデルに外部キー以外の値(:unit, :amount)を保存、もう片方のモデルにも値(:name)を保存させたいです。
具体的には、商品Aの情報を更新するページには、成分に関する動的なフォームがあり、「成分BをXグラム」と入力する欄があります。
発生している問題・エラーメッセージ
こちらの記事を参考に、モデルを編集する際、多対多のもう片方のモデルに同時に保存することはできました。(成分名の保存)
https://learn.co/lessons/has-many-through-forms-rails
しかし、中間モデルに値を保存することができない状況です。(分量、単位の保存)
該当のソースコード
モデル
# 商品モデル
class Product < ApplicationRecord
has_many :product_ingredients, dependent: :destroy
has_many :ingredients, through: :product_ingredients
accepts_nested_attributes_for :product_ingredients, allow_destroy: true
accepts_nested_attributes_for :ingredients
def ingredients_attributes=(ingredient_attributes)
ingredient_attributes.values.each do |ingredient_attribute|
ingredient = Ingredient.find_or_create_by(ingredient_attribute)
self.ingredients << ingredient
end
end
end
# 成分モデル
class Ingredient < ApplicationRecord
has_many :product_ingredients, dependent: :destroy
has_many :products, through: :product_ingredients
end
# 中間モデル
class ProductIngredient < ApplicationRecord
belongs_to :product
belongs_to :ingredient
end
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
<div class="text-right">
<%= f.fields_for :ingredients, @product.ingredients.build do |ingredients_fields| %>
<%= link_to_add_association '成分を追加', f, :ingredients,
data: {
association_insertion_node: '#detail-association-insertion-point',
association_insertion_method: 'append' }
%>
</div>
<table class="table table-list">
<thead>
<tr>
<th>成分</th>
<th>数量</th>
<th>単位</th>
<th></th>
</tr>
</thead>
<tbody id="detail-association-insertion-point">
<div class="form-group">
<%= render "ingredient_fields", f:ingredients_fields %>
<% end %>
</div>
</tbody>
</table>
_ingredient_fields.html.erb
<tr class="nested-fields">
<td><%= f.text_field :name %></td>
<%= f.fields_for :product_ingredients, @product.product_ingredients.build do |pi| %>
<td><%= pi.text_field :amount %></td>
<td><%= pi.select :unit, [["mg","mg"],["g","g"],["μg","μg"]] %></td>
<% end %>
<td><%= link_to_remove_association "削除", f %></td>
</tr>
色々と調べて試行錯誤してみてもこのような場合どうすればいいかわかりませんでした。
解決方法をご存知の方がいらっしゃればアドバイスいただけると大変嬉しいです。
よろしくお願いいたします。
補足情報(FW/ツールのバージョンなど)
動的フォームに関してはcocoonを使用しています。
-
気になる質問をクリップする
クリップした質問は、後からいつでもマイページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
クリップを取り消します
-
良い質問の評価を上げる
以下のような質問は評価を上げましょう
- 質問内容が明確
- 自分も答えを知りたい
- 質問者以外のユーザにも役立つ
評価が高い質問は、TOPページの「注目」タブのフィードに表示されやすくなります。
質問の評価を上げたことを取り消します
-
評価を下げられる数の上限に達しました
評価を下げることができません
- 1日5回まで評価を下げられます
- 1日に1ユーザに対して2回まで評価を下げられます
質問の評価を下げる
teratailでは下記のような質問を「具体的に困っていることがない質問」、「サイトポリシーに違反する質問」と定義し、推奨していません。
- プログラミングに関係のない質問
- やってほしいことだけを記載した丸投げの質問
- 問題・課題が含まれていない質問
- 意図的に内容が抹消された質問
- 過去に投稿した質問と同じ内容の質問
- 広告と受け取られるような投稿
評価が下がると、TOPページの「アクティブ」「注目」タブのフィードに表示されにくくなります。
質問の評価を下げたことを取り消します
この機能は開放されていません
評価を下げる条件を満たしてません
質問の評価を下げる機能の利用条件
この機能を利用するためには、以下の事項を行う必要があります。
- 質問回答など一定の行動
-
メールアドレスの認証
メールアドレスの認証
-
質問評価に関するヘルプページの閲覧
質問評価に関するヘルプページの閲覧
0
ちょっと推測になってしまうのですが。
案A.
今はテンプレートのループが product > ingredients > product_ingredientsとループしていると思うんですが、普通は product > product_ingredients > ingredientsとするケースのほうが多いとおもうんですよね。なので、それに変えてみるのがオススメです。(おそらく今後の拡張もこのスタイルのほうがやりやすいことが多いと思います。)
案B.
accepts_nested_attributes_for :product_ingredients, allow_destroy: true
をIngredientモデルにも追加してみてください。
もしかするとこれだけで解消するかも。
投稿
-
回答の評価を上げる
以下のような回答は評価を上げましょう
- 正しい回答
- わかりやすい回答
- ためになる回答
評価が高い回答ほどページの上位に表示されます。
-
回答の評価を下げる
下記のような回答は推奨されていません。
- 間違っている回答
- 質問の回答になっていない投稿
- スパムや攻撃的な表現を用いた投稿
評価を下げる際はその理由を明確に伝え、適切な回答に修正してもらいましょう。
15分調べてもわからないことは、teratailで質問しよう!
- ただいまの回答率 88.23%
- 質問をまとめることで、思考を整理して素早く解決
- テンプレート機能で、簡単に質問をまとめられる
質問への追記・修正、ベストアンサー選択の依頼
h_daido
2018/04/03 22:55
"親となるモデルを保存した"時に呼ばれるcontrollerのメソッドの記載が無いようにおもうのですが、そこを追記してもらえないですか?