2017-08-15 53 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

在繼續建模之前,先看看它們!

相關問題