2013-12-19 65 views
0

我有一個評論表單,其中還包含一個附件表單。Rails test for form in form

評價模型包含:

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 

我需要找出正確的代碼,以便附件字段的形式顯示出來,但註釋會如果未選擇附件,則創建。

也許我需要把代碼放在附件控制器中?

+0

那麼什麼是你的問題?你試過的結果不是你所期望的嗎?如果是這樣,你的結果是什麼,你期望什麼? –

+0

'@ comment.attachments'不能爲'nil',它總是返回一個'ActiveRecord :: Relation'對象,其中包含來自以ruby對象翻譯的數據庫的0個或更多記錄。要測試附件是否存在,使用'.present?'(測試數組是否包含至少一個元素):'@ comment.attachments.present?'---給你一點小貼士@Reddirt:從不使用像'.nil?'或'== nil?'或'!= nil?',總是使用'.present?'(或其相反的,'.blank?') – MrYoshiji

+0

謝謝@MrYoshiji - 但是我沒有正確思考。在「新建」部分進行測試只會改變附件字段是否顯示在表單上。我需要找出另一種方式。 – Reddirt

回答

0

我改變了評價模型如下:

accepts_nested_attributes_for :attachments, :reject_if => lambda { |a| a[:attach].blank? }, :allow_destroy => true 
1

你可以使用Rails的present?方法來檢查對象不是空白:

@comment.attachments.build if @comment.attachments.present? 
+0

感謝您的幫助! – Reddirt

+0

該代碼有效 - 但它沒有做我想要的。 – Reddirt