我正在關注 Ruby on Rails Guides Active Record Aossications 以及此處的其他一些執行緒,但不確定我是否正確設定了它:
產品有多種圖片集(例如顏色、口味、款式) 一個產品品種只有一個圖片集(尺寸--> 顏色襯衫)
所以我認為這些關聯實際上應該是:
Products
--has_many :product_varieties
--has_many :variety_image_sets, through: :product_varieties
Product Varieties
--belongs_to :product
--has_one :variety_image_set
Variety Image Sets
--belongs_to :product_variety
我從檔案、章節和段落的 Rails 指南示例中得到了這個設定想法,但不幸的是,它只有在我對產品品種使用 has_many :variety_image_sets 時才有效。
我的課程如下:
class Product < ApplicationRecord
belongs_to :product_category
has_many :product_varieties
has_many :variety_image_sets, through: :product_varieties
end
class ProductVariety < ApplicationRecord
belongs_to :product
has_many :variety_image_sets
end
class VarietyImageSet < ApplicationRecord
belongs_to :product_variety
end
對于 Variety Image Set 模型,我在遷移中有一個 product_variety:references。
我能夠為每個單獨的產品品種創建一個品種影像集,但我希望它能夠重復使用產品集(例如,黑色襯衫可以有多種尺寸)。
現在,繼續進行系列選擇:一旦我們定義了至少一個品種影像集,就可以在創建新產品品種時使用系列選擇。
這個有效:
= form_with(model: [@product, product_variety]) do |form|
= form.collection_select(:variety_image_set_ids, VarietyImageSet.all, :id, :label, { prompt: true }, {multiple: false})
在我的控制器的 product_variety_params 中:
def product_variety_params
params.require(:product_variety).permit(:size, :unit_amount, :current_inventory, :variety_image_set_ids)
end
如果我嘗試將 VarietyImageSet.all 更改為variety.variety_image_sets,則選擇選單變為空。此外,一個 Product 品種已經定義了一個,當我嘗試將它分配給不同的品種時,其他品種從第一個品種“竊取”它,而不是同時分配到該品種影像集。
請指教。謝謝
更新根據第一個答案中的建議,我已經更新了關聯。我現在將 Variety Image Sets 創建為 Product 的嵌套資源,而不是在 Product Variety 下。這有效。
現在,我單擊 Product Variety 的 edit 并希望使用 collection_select 為其分配 Pariety Image Set:
= form.collection_select(:variety_image_sets_id, VarietyImageSet.all, :id, :label, { prompt: true }, {multiple: false}) 更新引數:def product_variety_params params.require(:product_variety).permit(:size, : unit_amount, :current_inventory, :variety_image_sets_id) 結束
但是,我收到“必須存在各種影像集”的錯誤訊息。
最后,VarietyImageSet.all 將給我所有這些,我想將它們過濾為僅屬于產品的那些。@product.variety_image_sets 雖然回傳未定義的方法“variety_image_sets”。
= form_with(model: [@product, product_variety]) do |form|

uj5u.com熱心網友回復:
您應該使用ProductVariety作為具有以下關聯的中間表:
class Product < ApplicationRecord
belongs_to :product_category
has_many :product_varieties
has_many :variety_image_sets, through: :product_varieties
end
class ProductVariety < ApplicationRecord
belongs_to :product
belongs_to :variety_image_sets
end
class VarietyImageSet < ApplicationRecord
has_many :product_variety
end
現在Product表將包含您的所有產品。VarietyImageSet將包含產品的所有品種,而ProductVariety表將存盤哪個產品具有哪個品種。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370845.html
標籤:红宝石轨道
