Multiple Images for Multiple Models - Paperclip, Rails

让人想犯罪 __ 提交于 2019-12-08 02:01:30

问题


I have four models, let's call them Cars and Houses. Users can have multiple cars, and multiple houses. Cars and Houses belong to Users. I'd like users to be able to upload multiple photos of their cars, and multiple photos of their houses, and from what I've read this means creating a new model called 'Photos'. Is it possible for two different models to both have_many Photos, and for Photos to belong_to more than one model? I'm using Ruby 2.0.0 and Rails 4.

Sketch / PseudoRuby

User
  has_many :cars
  has_many :houses

Car
  belongs_to :user
  has_many :photos

House
  belongs_to :user
  has_many :photos

Photo
  belongs_to :car, :house

Is this relationship ok? I wasn't sure if I had to make separate models for the photos of Car and House.


回答1:


From a Rails standpoint, yes you can do it. The belongs_to association tells Rails to keep the foreign_key in the Photo model. So in your example, your photos table will have 2 foreign keys :

  • car_id which will point to the associated car id (primary key) from the cars table.
  • house_id which will point to the associated house id (primary key) from the house table.

Now, from the paperclip standpoint, you can have as many photos for a particular model as you want. But, in order to have the same Photo model associated to both House and Car, you need to use polymorphic association. Your model will be similar to this :

class Photo < ActiveRecord::Base
 belongs_to :imageable, polymorphic: true
 has_attached_file :photo, styles: {}

end

class Car < ActiveRecord::Base
  has_many :photos, as: :imageable
end

class House < ActiveRecord::Base
  has_many :photos, as: :imageable
end   

You can get more information about polymorphic associations here: http://guides.rubyonrails.org/association_basics.html



来源:https://stackoverflow.com/questions/19279553/multiple-images-for-multiple-models-paperclip-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!