如何将上传的图片与模型相关联

时间:2011-07-18 06:40:23

标签: ruby-on-rails-3

我允许用户上传照片。此照片使用回形针存储。我用来上传和存储照片的模型称为上传。

# 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
#

有一个我希望链接到上传照片的模型。它被称为消息。

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

我想使用upload_id将图片链接到消息模型。

然而,这意味着关联将如下

Message

belongs_to :upload


Upload

has_one :message

这似乎有点奇怪。要为说明添加更多内容,我还会上传其他模型(如用户)的文件。所以我真的想在表中为每个使用上传的模型存储上传ID。

然后我如何从消息实例访问上传

@ message.upload_id.upload? @ user.upload_id.upload?

提前致谢

1 个答案:

答案 0 :(得分:0)

更正您的模型类:

class Message < ActiveRecord::Base
  has_one :upload
end

class Upload < ActiveRecord::Base
  belongs_to :message
end

创建迁移以将字段message_id添加到上传表格中。

然后使用@message.upload访问与邮件关联的上传模型。