我有一个使用 Carrierwave 作为上传器将文件上传到雾存储的模型。
问题是当我创建 100 个模型对象时,它们都上传了同一个文件。
我需要模型实例来引用相同的上传文件。有许多模型实例和 1 个文件的一对多关系。
目前该文件是我的模型messages.rb上称为附件的属性 -
class Message < ActiveRecord::Base
attr_accessible :body, :remote_attachment_url, :from, :to, :status, :attachment, :campaign, :version, :user_id, :SmsId, :response, :response_code, :client_id
mount_uploader :attachment, AttachmentUploader
end
当我在MessagesController.rb中创建一个新的 Message 实例时,我在我的控制器中设置了附件-
recipients.each do |value|
@message = Message.new(:attachment => params[:message][:attachment], :campaign => message[:campaign], :version => message[:version], :to => value, :body => body, :status => status, :user_id => current_user.id, :client_id => client.id )
end
我正在使用 Ruby 2.0,Rails 4
解决方案:
我通过将附件文件推送到新模型中然后在消息对象和附件对象之间建立关联来解决此问题。
消息控制器:
@attachment = Attachment.create(params[:message][:attachment_attributes])
recipients.each do |value|
@message = Message.new(:campaign => params[:message][:campaign], :version => params[:message][:version], :to => value, :body => params[:message][:body], :status => status, :user_id => current_user.id, :client_id => client.id )
@message.attachment = @attachment
end
消息模型:
attr_accessible :attachment_id, :attachment_attributes
belongs_to :attachment
accepts_nested_attributes_for :attachment
附件型号:
attr_accessible :attached, :remote_attached_url, :attachment_attributes
mount_uploader :attached, AttachmentUploader