Multiple models and Paperclip

2019-09-04 16:34发布

问题:

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