Multiple models and Paperclip

 ̄綄美尐妖づ 提交于 2019-12-25 18:35:22

问题


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

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.

So can both models have a

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

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

Thanks


回答1:


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

example:

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

belongs_to :mediable, ploymorphic: true

User, Article, Post model or another:

has_many :medias, as: mediable



来源:https://stackoverflow.com/questions/18073924/multiple-models-and-paperclip

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