Reputation: 5953
I'm trying to create a single form that allows for the creation of a Comment and an associated Attachment
Comments Model has:
class Comment < ActiveRecord::Base
has_many :attachments
accepts_nested_attributes_for :attachments
end
Comments Controller has:
# GET /comments/new
# GET /comments/new.json
def new
@comment = Comment.new
@worequest = params[:worequest_id]
respond_to do |format|
format.html # new.html.erb
format.json { render json: @comment }
end
end
In the Comment Form, I'm trying to add this:
<%= simple_form_for @comment, :html => {:class => 'form-horizontal'} do |f| %>
(CODE FOR COMMENT)
<% f.fields_for @attachments do |builder| %>
<%= builder.input :name, :label => 'Attachment Name' %>
<%= builder.file_field :attach, :label => 'Attachment File' %>
<% end %>
But, I'm getting this error:
undefined method `model_name' for NilClass:Class
Thanks for the help!
Upvotes: 0
Views: 80
Reputation: 38645
As @Donovan commented, you're not defining @attachments
, hence the error. I had guessed that error was from the form_for
declaration.
Update your controller new
action's code to build attachments on @comment
:
# GET /comments/new
# GET /comments/new.json
def new
@comment = Comment.new
@comment.attachments.build # Add this line
@worequest = params[:worequest_id]
respond_to do |format|
format.html # new.html.erb
format.json { render json: @comment }
end
end
Then update your form view code to:
<%= simple_form_for @comment, :html => {:class => 'form-horizontal'} do |f| %>
(CODE FOR COMMENT)
<%= f.fields_for :attachments do |builder| %>
<%= builder.input :name, :label => 'Attachment Name' %>
<%= builder.file_field :attach, :label => 'Attachment File' %>
<% end %>
You could also chose to define @attachments
in your controller action and use that in your view instead. By doing f.fields_for :attachments
the current object's (i.e. @comment
in this case) attachments association is used, so defining @attachments
in controller is not necessary.
Upvotes: 1