简体   繁体   English

has_one:through和has_many:through在同一关联中

[英]has_one :through and has_many :through in the same association

I am trying to model a relationship between Image model and Page model with the following constraints: 我正在尝试使用以下约束为图像模型和页面模型之间的关系建模:

1 - a page can have a maximum of one image ( 0 image is also acceptable ) 1-一个页面最多可以包含一张图像(也可以接受0张图像)

2 - an image is can appear in many pages. 2-图像可以出现在许多页面中。

so the relationship could be surmised as following: 因此可以推测这种关系如下:

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

Usually this associations either exist with both classes Image and Page with has_many :through or both having has_one :through Is it possible to mix between has_one :through and has_many :through in this case ? 通常,此关联在具有has_many:through的Image和Page类中都存在,或者在具有has_one:through的情况下都存在,在这种情况下是否可以在has_one:through和has_many:through之间混合使用? ActiveRecord does not mention this particular case ActiveRecord没有提到这种特殊情况

PS: I chose to use the join model way since i have other models that could have the same images as well with different constraints (has_many instead of has_one) PS:我选择使用联接模型方式,因为我还有其他模型,它们可能具有相同的图像以及不同的约束(has_many代替has_one)

Thanks for your help! 谢谢你的帮助!

The code above didn't work... And i found a median solution to implement the schema that i needed. 上面的代码不起作用...而且我找到了实现我需要的架构的中位解决方案。

The final code looks like : 最终代码如下:

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

When i use rails_admin to edit my models, i get just the thing when it comes to add a new image and the validation in Imageable ensure the ditor do not mess around with the specifications... 当我使用rails_admin编辑我的模型时,添加新图像以及Imageable中的验证确保了ditor不会弄乱规范……

It is little bit weird as a solution, but believe me, it is well adapted for the context of the app that i am developping... 作为解决方案这有点奇怪,但是请相信我,它非常适合我正在开发的应用程序的上下文...

I am posting it so if somebody had similar concern. 我发布它是为了让有人对此有类似的关注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM