2017-08-15 55 views
0

你好Rails社区!2个不同的模型共享1个独特的照片模型

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

我有2个型动物模型:汽车房子 论文机型才能拥有多张照片。

我的问题是:

  • 是否有可能使用的汽车和房子1种照片模式或我需要建立1个cars_photos模型和1个house_photos模型
  • 如果有可能,我怎么能生成我的照片模型?

=>选项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 

此选项的问题是,照片​​必须与汽车以及与房子挂钩。女巫不好。 =>我要照片与汽车或与房子挂钩

我不知道如何着手?

THX!

+0

请参见[导游](HTTP:/ /guides.rubyonrails.org/association_basics.html#the-has-many-through-association)has_many:通过Association。 – jvillian

+0

您可以使用多态关联。官方的Rails指南使用图像关系作为示例,它完全符合您的要求:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations – MrYoshiji

回答

1

这几乎是准确的原型polymorphicRails guides

$ 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表:imageable_id:integer这将是关联对象的id列和imageable_type:string这将是关联的o的字符串化类名称bject。这允许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 

您可以将Photo添加到CarCar.find(params[:car_id]).photos.create和分配CarPhotoPhoto.new imageable: Car.find(params[:car_id])

+0

Hello m.simon borg Thx for your answer 我测试你的明天解决:) –

+0

你好m.simon博格。它工作完美!来自法国巴黎的许多Thx ;-) –

0

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

有两个主要的宝石 照片上传:paperclipcarrierwave

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

相关问题