开发者

How to associate an uploaded picture to a models

开发者 https://www.devze.com 2023-03-20 19:28 出处:网络
I allow users to upload a photo. This photo is stored using paperclip. The model that I use to upload and store the photo is called Upload.

I allow users to upload a photo. This photo is stored using paperclip. The model that I use to upload and store the photo is called Upload.

# Table name: uploads
#
#  id                 :integer         not null, primary key
#  created_at         :datetime
#  updated_at         :datetime
#  photo_file_name    :string(255)
#  photo_content_type :string(255)
#  photo_file_size    :integer
#  photo_updated_at   :datetime
#

have a model that I wish to link to the uploaded photo. It is called Message.

Table name messages
#  content            :string(255)
#  upload_id               :string(255)
#  created_at         :datetime
#  updated_at         :datetime

I want to use the upload_id to link the image to the message model.

However this means the association will be as follows

Message

belongs_to :upload


Upload

has_one :message

This seems a bit strange. To add more to the descr开发者_如何转开发iption I will also upload files for other models such as User. So I really would like to store the upload id in the table for each model that uses an upload.

Then how can I access the upload from an instance of a message

@message.upload_id.upload?

@user.upload_id.upload?

Thanks in advance


Correct your models classes:

class Message < ActiveRecord::Base
  has_one :upload
end

class Upload < ActiveRecord::Base
  belongs_to :message
end

Create a migration to add a field message_id into uploads table.

And then use @message.upload to access your upload model associated with the message.

0

精彩评论

暂无评论...
验证码 换一张
取 消