多种型号和回形针 [英] Multiple models and Paperclip

查看:146
本文介绍了多种型号和回形针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用回形针将多个模型全部都使用一个中央模型作为其图像。因此,例如,我有一个照片模型,将使用回形针存储其网址等

I was wondering if it is possible to have multiple models all using one central model for its images using paperclip.. So for example I would have a photo model which would use paperclip to store its urls etc

在我的情况下,我有2个模型,投资组合和发布模型,两者都有一个表格,可让您将图像和其他属性上传到模型。

In my case I have 2 models, portfolio and post, both of which have a form which allow you to upload images and other attributes to the model.

两个模型都可以拥有

has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos

还是我需要为每个创建单独的模型照片,即photo1,photo2可以这样做吗?以便投资组合模型可以提供一个图像而后期模型可以提供另一个图像呢?

or would i need to create separate models for each of the photos, ie photo1, photo2 to do this? so that the portfolio model feeds off one and post model feeds off another for its images?

我只是想更好地理解并保持干燥状态

I am just looking to get a better understanding and keep things DRY

谢谢

推荐答案

您可以使用多态关联,其中一个以上的模型将具有很多照片。

You can use polymorphic associations, where more then one model will have many photos.

http:/ /guides.rubyonrails.org/association_basics.html#polymorphic-associations

http://railscasts.com/episodes/154-polymorphic-association-revised

示例:

您的模型将称为媒体,并将属于mediable,其中mediable可能是文章,用户,帖子等。

Your model will be called media and will belong to mediable, where mediable might be article, user, post, etc..:

属于:中等,多形:true

用户,文章,宝st模型或其他模型:

User, Article, Post model or another:

has_many:medias,如:mediaable

这篇关于多种型号和回形针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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