Ruby on rails Rails测试表单中的内容
我有一个评论表单,其中还包含一个附件表单 注释模型包含:Ruby on rails Rails测试表单中的内容,ruby-on-rails,Ruby On Rails,我有一个评论表单,其中还包含一个附件表单 注释模型包含: accepts_nested_attributes_for :attachments <%= f.fields_for :attachments do |builder| %> <%= builder.input :name, :label => 'Attachment Name' %> <%= builder.file_field :attach %> <% end %>
accepts_nested_attributes_for :attachments
<%= f.fields_for :attachments do |builder| %>
<%= builder.input :name, :label => 'Attachment Name' %>
<%= builder.file_field :attach %>
<% end %>
def new
@comment = Comment.new
@comment.attachments.build
评论表包含:
accepts_nested_attributes_for :attachments
<%= f.fields_for :attachments do |builder| %>
<%= builder.input :name, :label => 'Attachment Name' %>
<%= builder.file_field :attach %>
<% end %>
def new
@comment = Comment.new
@comment.attachments.build
如果用户添加了附件,则一切正常
我希望用户能够提交一个评论或没有附件
现在,如果用户输入没有附件的注释,表单将重新显示,并且注释不会被创建
如果我试图在没有附件的情况下发布新评论,则记录如下:
Started POST "/comments" for 127.0.0.1 at 2013-12-19 10:34:31 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"A6MOeMgoGUDmGiJr9PWinHVTAa7X63fgtA7+2my0A2Y=", "comment"=>{"user_id"=>"1", "status_date"=>"2013-12-19", "worequest_id"=>"10", "statuscode_id"=>"", "comments"=>"test", "attachments_attributes"=>{"0"=>{"name"=>""}}}, "_wysihtml5_mode"=>"1", "commit"=>"Save Comment"}
Tenant Load (0.3ms) SELECT "tenants".* FROM "tenants" WHERE "tenants"."subdomain" = 'ame' LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."tenant_id" = 1 AND "users"."id" = 1 LIMIT 1
(0.1ms) BEGIN
(0.1ms) ROLLBACK
我需要找出正确的代码,以便在表单中显示附件字段,但如果未选择附件,则会创建注释
也许我需要在附件控制器中添加代码?您可以使用Rails方法检查对象是否为空:
@comment.attachments.build if @comment.attachments.present?
我将注释模型更改为:
accepts_nested_attributes_for :attachments, :reject_if => lambda { |a| a[:attach].blank? }, :allow_destroy => true
那么你的问题是什么?你尝试的结果是否与你预期的不同?如果是这样,您的结果是什么?您期望得到什么?
@comment.attachments
不能是nil
,它总是返回一个ActiveRecord::Relation
对象,其中包含在ruby对象中翻译的DB中的0条或多条记录。若要测试附件是否存在,请使用.present?
(测试数组是否包含至少一个元素):@comment.attachments.present?
——给您的一点提示@Reddirt:不要使用.nil?
或==nil?
或!=无?
,请始终使用.present?
(或其反面,.blank?
)谢谢@MrYoshiji-但是,我没有正确思考。在新部分中执行测试只会更改附件字段是否显示在表单上。我需要找出另一种方法。你能重新键入你的问题,以消除无用的代码/文本,并添加相关的代码/文本片段吗?请明确你到底想要什么。(例如:在创建操作时,如果用户没有发送任何附件,我不想创建注释对象)