我使用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
答案 0 :(得分:2)
这应该在您的模型中完成,例如:
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