[英]Has_many of different models association in Rails
I have a few different models which I would like to add multiple images to. 我有几种不同的模型,我想添加多个图像。
I have an image model with belongs_to
associations set up to the different owning models (each of these owning models has has_many :images
defined). 我有一个图像模型,其中的belongs_to
关系设置为不同的拥有模型(每个拥有模型都有has_many :images
定义)。
I would like to know what's the appropriate migration I should create in order to add an image_ids
column to each of owning models. 我想知道什么是合适的迁移,以便将image_ids
列添加到每个拥有的模型中。
I assume something like this... 我认为是这样的...
rails g migration AddImagesToBusinesses images businesses image_ids:integer
However, I'm confused as I believe that you can only make one association this way and it would need to be completed by adding a column to the images table to identify the id of the model it belongs to (here there are a few different models). 但是,我感到困惑,因为我相信您只能以这种方式建立一个关联,并且需要通过在imagess表中添加一列来标识其所属的模型的ID(此处有一些不同之处)来完成关联楷模)。
Thank you for your help. 谢谢您的帮助。
I think you need Polymorphic associations. 我认为您需要多态关联。 See documentaions here. 请参阅此处的文献 。
As you concern about relationship of image to other model. 当您关注图像与其他模型的关系时。 You should try polymorphic associations like this. 您应该尝试这样的多态关联。
Generate the Image model: 生成图像模型:
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :file_id
t.boolean :featured
t.references :imageable, polymorphic: true, index: true
t.timestamps null: false
end
end
end
Update the Image model: 更新图像模型:
class Image < ActiveRecord::Base
attachment :file
belongs_to :imageable, polymorphic: true
end
Add association to other models like this 将关联添加到其他这样的模型
class Model < ActiveRecord::Base
has_many :images, as: :imageable, dependent: :destroy
accepts_attachments_for :images, attachment: :file
end
For more details you Ruby on Rails Guide . 有关更多详细信息,请参见Ruby on Rails指南 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.