Brandon Harris | Nested Model Forms and attachment_fu

Nested Model Forms and attachment_fu

I think that a lot of Rails developers have moved on to Paperclip . Most of us started with attachment_fu , and I am willing to wager that we still have projects floating around using attachment_fu.

I updated one of these older projects to 2.3.4, and created a new form utilizing the built in nested form handling as of 2.3.

My models look like this:

 1 class Article < ActiveRecord::Base
 2   has_one :report
 3   accepts_nested_attributes_for :report
 4 end
 5 
 6 class Report < ActiveRecord::Base
 7   belongs_to :article
 8   has_attachment(
 9     :storage => :file_system,
10     :file_system_path => 'public/reports',
11     :max_size => 2.megabytes,
12     :content_type => 'application/pdf'
13   )
14   validates_as_attachment
15 end

The idea is that an article can have a pdf attachment. The view code for the nested form should look like this:

1  <%form_for :article, :url => admin_articles_url, :html => {:multipart => true} do |f| %>
2     <%=f.label :title%>
3     <%=f.text_field :title%>
4     ...
5     <%f.fields_for :report do |e|%>
6       <%=e.label :report %>
7       <%=e.file_field :uploaded_data%>
8     <%=f.submit 'Create'%>
9   <%end%>

Then in your parameters, you should see params[:article][:report_attributes], and by having accepts_nested_attributes in the Article model, Rails takes care of the rest.

However, I received this error:

Report(#70166977052900) expected, got HashWithIndifferentAccess(#70167015178720)

I google around, and found this thread which doesn’t provide a solution, in fact no where could I find the solution. So I did some of my own digging, and I noticed that my parameters looked like this:

params[:article] and params[:report]

I wasn’t seeing the expected:

params[:article][:report_attributes]

So given this information, I tried this:

1   <%form_for :article, :url => admin_articles_url, :html => {:multipart => true} do |f| %>
2     <%=f.label :title%>
3     <%=f.text_field :title%>
4     ...
5     <%f.fields_for :report_attributes do |e|%>
6       <%=e.label :report %>
7       <%=e.file_field :uploaded_data%>
8     <%=f.submit 'Create'%>
9   <%end%>

Voila! Problem solved. I haven’t dug into the code for Rails and Attachment_Fu to see why this needs to be done, but if you are having this problem and need it fixed, just append “_attributes” to your nested child model name in the view.

Tags

  • e (1)