Question

Newbie on Rails 3.2.14, testing on Heroku, uploading image files to S3 with s3_direct_upload gem.

I've got the gem working fine. Drag and drop, progress bars and direct upload to S3 work great. The upload is tied to an Attachment model. The new record is created properly on upload. Fine so far.

The issue I'm having is that I want to set the parent_id field of the new record but don't know how to pass it in. The gem doesn't use a conventional form to submit the upload, it's handled by via javascript:

<%= s3_uploader_form callback_url: attachments_url, callback_param:
"attachment[attachment_url]", id: "myS3Uploader" do %>
    <%= file_field_tag :file, multiple: true %>
<% end %>

The create action in attachments_controller.rb:

def create
  @attachment = Attachment.create(params[:attachment])
end

calls a javascript view create.js.erb:

<% if @attachment.new_record? %>
  alert("Failed to upload attachment: <%= j @attachment.errors.full_messages.join(', ').html_safe %>");
<% else %>
  $("#attachments").prepend("<%= j render(@attachment) %>");
<% end %>

which checks if the record save worked and adds the new upload thumbnail to the current view.

Since I'm not dealing with a regular form or create action I'm a bit stumped.

I can set default values in the Attachment model with a before_save:

before_save :set_defaults

def set_defaults
  self.name = "Photo"
  self.parent_id = 1
end

but the parent_id will be defined on the page where the uploads are done, during the creation of the parent object (i.e. a blog post).

I know I should be using has_many and belongs_to and they're set up and working fine but since I'm not using a conventional form to submit the data I don't know how to assign the parent_id.

I've tried passing parent_id in the form and accessing it in the model:

<%= s3_uploader_form callback_url: attachments_url(:parent_id => 99), callback_param:
"attachment[attachment_url]", id: "myS3Uploader" do %>

It didn't work and I know I'm not supposed to be accessing params inside the model anyway.

Any help to get me past this point would be greatly appreciated.

Was it helpful?

Solution

OK, so I read a lot of questions and answers on here and finally pieced it together myself.

So I was on the right track passing in (:parent_id => 99) but I shouldn't have been trying to use it in the model, I should be using it in the controller.

I changed the create method in the controller to fetch the draft Parent object I had created and to make the new Attachment record a child of it:

def create
  @parent = Parent.find(params[:parent_id])
  @attachment = @parent.attachments.create(params[:attachment])
end

The value of the :parent_id passed in was coming from the 'new' parent form so it was actually (:parent_id => @parent.id).

It's all working fine now. It was just my utter lack of experience holding me back :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top