2个不同的模型共享1个独特的照片模型

2 different Model share 1 unique Photo Model

您好Rails社区!

我不知道如何构造我的不同模型。

我有两种不同的模型:汽车房子 这些模型可以有多张照片。

我的问题是:

=> 选项 1

rails g model Photo name:string, description:text car:references house:references

Car.rb

has_many :photos

House.rb

has_many :photos

Photo.rb

belongs_to :car
belongs_to :house

此选项的问题是照片必须与汽车和房屋相关联。 不好。 => 我希望照片与汽车或房屋相关联

我不知道如何进行...

谢谢!

是的,您可以重复使用汽车和房子的照片。

有两个主要宝石 照片上传:paperclip and carrierwave.

在继续建模之前先看看它们!

这几乎是 Rails guides

中的 polymorphic 关联原型
$ rails g model Photo name:string description:text imageable:references{polymorphic}:index

生成此迁移文件

class CreatePhotos < ActiveRecord::Migration[5.1]
  def change
    create_table :photos do |t|
      t.string :name
      t.text :description
      t.references :imageable, polymorphic: true

      t.timestamps
    end
  end
end

t.references :imageable, polymorphic: true 将在 photos table 上为您提供两列:imageable_id:integer 将是关联对象的 id 列, imageable_type:string 将是关联对象的字符串化 class 名称。这允许 photos 与一个关联上的任何模型交互并属于任何模型。

那么你的模型应该是这样的

class Photo < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Car < ApplicationRecord
  has_many :photos, as: :imageable
end

class House < ApplicationRecord
  has_many :photos, as: :imageable
end

您可以使用 Car.find(params[:car_id]).photos.createPhoto 添加到 Car,并使用 Photo.new imageable: Car.find(params[:car_id])[= 将 Car 分配到 Photo 27=]