[英]has_one :through and has_many :through in the same association
我正在嘗試使用以下約束為圖像模型和頁面模型之間的關系建模:
1-一個頁面最多可以包含一張圖像(也可以接受0張圖像)
2-圖像可以出現在許多頁面中。
因此可以推測這種關系如下:
class Image < ActiveRecord :: Base
has_many :pages, :through :imageables
end
class Page < ActiveRecord :: Base
has_one :image, :through :imageables
end
class Imageable < ActiveRecord :: Base
belongs_to :image
belongs_to :page
end
通常,此關聯在具有has_many:through的Image和Page類中都存在,或者在具有has_one:through的情況下都存在,在這種情況下是否可以在has_one:through和has_many:through之間混合使用? ActiveRecord沒有提到這種特殊情況
PS:我選擇使用聯接模型方式,因為我還有其他模型,它們可能具有相同的圖像以及不同的約束(has_many代替has_one)
謝謝你的幫助!
上面的代碼不起作用...而且我找到了實現我需要的架構的中位解決方案。
最終代碼如下:
class Image < ActiveRecord :: Base
has_many :pages, :through :imageables
end
class Page < ActiveRecord :: Base
has_many :image, :through :imageables
accepts_nested_attributes :images, allow_destroy => true
end
class Imageable < ActiveRecord :: Base
belongs_to :image
belongs_to :page
validates_uniqueness_of :page_id
end
當我使用rails_admin編輯我的模型時,添加新圖像以及Imageable中的驗證確保了ditor不會弄亂規范……
作為解決方案這有點奇怪,但是請相信我,它非常適合我正在開發的應用程序的上下文...
我發布它是為了讓有人對此有類似的關注。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.