我正在尝试创建一个允许创建Comment和相关附件的单个表单
评论模型有:
class Comment < ActiveRecord::Base
has_many :attachments
accepts_nested_attributes_for :attachments
end
评论控制器:
# 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
在评论表格中,我试图添加:
<%= 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 %>
但是,我收到了这个错误:
undefined method `model_name' for NilClass:Class
感谢您的帮助!
答案 0 :(得分:1)
正如@Donovan评论的那样,你没有定义@attachments
,因此错误。我猜这个错误来自form_for
声明。
更新您的控制器new
操作代码以在@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
然后将表单视图代码更新为:
<%= 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 %>
您还可以选择在控制器操作中定义@attachments
,然后在视图中使用它。通过执行当前对象的f.fields_for :attachments
(在这种情况下为@comment
),使用附件关联,因此不需要在控制器中定义@attachments
。