多个模型的多个图像 - Paperclip、Rails [英] Multiple Images for Multiple Models - Paperclip, Rails

查看:49
本文介绍了多个模型的多个图像 - Paperclip、Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四种模型,我们称它们为汽车和房屋.用户可以拥有多辆汽车和多间房屋.汽车和房屋属于用户.我希望用户能够上传他们汽车的多张照片和他们房子的多张照片,据我所知,这意味着创建一个名为照片"的新模型.两个不同的模型是否有可能同时拥有_许多照片,而照片属于多个模型?我使用的是 Ruby 2.0.0 和 Rails 4.

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.

草图/伪Ruby

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.

推荐答案

从 Rails 的角度来看,是的,您可以做到.Belongs_to 关联告诉Rails 将foreign_key 保留在Photo 模型中.因此,在您的示例中,您的照片表将有 2 个外键:

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 将指向汽车表中关联的汽车 ID(主键).
  • house_id 将指向房屋表中关联的房屋 ID(主键).

现在,从回形针的角度来看,您可以拥有任意数量的特定模型的照片.但是,为了将相同的 Photo 模型与 House 和 Car 关联,您需要使用多态关联.您的模型将与此类似:

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   

您可以在此处获得有关多态关联的更多信息:http://guides.rubyonrails.org/association_basics.html

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

这篇关于多个模型的多个图像 - Paperclip、Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆