Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I reference the same Carrierwave uploaded file in multiple Ruby model instances without reprocessing
    primarykey
    data
    text
    <p>I have a model that is using Carrierwave as an uploader to upload files to fog storage. </p> <p>The problem is that when I create say 100 model objects they all upload the same file. </p> <p>I need the model instances to reference the same uploaded file. A <strong>one-to-many</strong> relationship where there are many model instances and 1 file. </p> <p>At the moment the file is an attribute called attachment on my model messages.rb -</p> <pre><code> class Message &lt; 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 </code></pre> <p>I set attachment in my controller when I create a new Message instance in <strong>MessagesController.rb</strong> - </p> <pre><code> recipients.each do |value| @message = Message.new(:attachment =&gt; params[:message][:attachment], :campaign =&gt; message[:campaign], :version =&gt; message[:version], :to =&gt; value, :body =&gt; body, :status =&gt; status, :user_id =&gt; current_user.id, :client_id =&gt; client.id ) end </code></pre> <p>I'm using Ruby 2.0, Rails 4 </p> <hr> <h1>Solution:</h1> <p>I fixed this by pushing my attachment file into a new model then building an association between the message object and the attachment object. </p> <p><strong>MessagesController:</strong></p> <pre><code>@attachment = Attachment.create(params[:message][:attachment_attributes]) recipients.each do |value| @message = Message.new(:campaign =&gt; params[:message][:campaign], :version =&gt; params[:message][:version], :to =&gt; value, :body =&gt; params[:message][:body], :status =&gt; status, :user_id =&gt; current_user.id, :client_id =&gt; client.id ) @message.attachment = @attachment end </code></pre> <p><strong>Message model:</strong></p> <pre><code> attr_accessible :attachment_id, :attachment_attributes belongs_to :attachment accepts_nested_attributes_for :attachment </code></pre> <p><strong>Attachment model:</strong></p> <pre><code>attr_accessible :attached, :remote_attached_url, :attachment_attributes mount_uploader :attached, AttachmentUploader </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload