How do I have optional nested resources submitted through a form in Rails 3?
Iam using simple_form. The user can create a message. Optionally, they can attach a contact. Right now, if they don't attach a contact, a new Con开发者_Python百科tact is still created?
How can I only associate and create a new Contact when that Contact portion of the form is filled out?
Here is the form I use now:
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
This should be done in your model, something like:
accepts_nested_attributes_for :contact, :allow_destroy => true, :reject_if => lambda { |c| c[:first_name].blank? && c[:last_name].blank? }
Or whatever condition you prefer.
The dirty way, while Rails bugs are being fixed. In your model:
after_save :check_nil_contact
def check_nil_contact
if contact.first_name.blank?
contact.destroy
end
end
精彩评论