如何通过Rails 3中的表单提交可选的嵌套资源?

| 我使用simple_form。用户可以创建一条消息。 (可选)他们可以附加联系人。现在,如果他们不附加联系人,还会创建新的联系人吗? 填写表单的“联系方式”部分后,我如何才能仅关联并创建一个新的联系方式? 这是我现在使用的表格:
1 = simple_form_for @message, :remote => true do |f|
  2   #message_form
  3     = f.error_messages
  4     %p
  5       = f.input :account_name, :url => autocomplete_account_name_messages_path, :size => 40, :as => :autocomplete
  6     %p
  7       = f.input :subject
  8       %br 
  9       = f.input :body, :as => :text, :input_html => { :class => \'autogrow\', :rows => 5, :cols => 30, :maxlength => 140  }
 10     = hidden_field_tag :sender_id, params[:sender_id]
 11     = hidden_field_tag :receiver_id, params[:id]
 12 
 13     = f.submit \'Give\'
 14     = f.submit \'Request\'
 15     
 16     #add_contact_btn
 17       = link_to \"Add Contact\"
 18     
 19       #contact_form
 20         = simple_fields_for :contact do |fc|
 21           %p
 22             = fc.input :first_name
 23           %p
 24             = fc.input :last_name
 25             = fc.input :email
 26             = fc.input :title
 27             = fc.input :office_phone
    
已邀请:
        这应该在您的模型中完成,例如:
accepts_nested_attributes_for :contact, :allow_destroy => true, :reject_if => lambda { |c| c[:first_name].blank? && c[:last_name].blank? }
或您喜欢的任何条件。 修正了Rails错误的肮脏方式。在您的模型中:
after_save :check_nil_contact

def check_nil_contact
  if contact.first_name.blank?
    contact.destroy
  end
end
    

要回复问题请先登录注册