Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

an example of a nested form in simple form?

I am still struggling both writing the controller and the actual form to be able to nest one form in another with an optional model?

I have Message which has many contacts

When submitting a message, I want to add a contact optionally.

I have this as an example:

= simple_form_for Message.new, :remote => true do |f|
  #message_form
    = f.error_messages
    %p
      = f.input :account_name, :url => autocomplete_account_name_messages_path, :size => 40, :as => :autocomplete
    %p
      = f.input :topic, :required => true,
                :input_html => {:size => 30}

    #add_contact_btn
      = link_to "Add Contact"

      #contact_form
        = f.simple_fields_for :contactd do |fc|
        = fc.input :email
        = fc.input :first_name
        = fc.input :last_name

    = f.submit 'Give'
    = f.submit 'Request'

For Message.rb model, I have the following:

has_many :contacts
accepts_nested_attributes_for :contacts, :reject_if =>:all_blank

Note: When I used :contacts in the simple_fields_for it didn't work, so it is singular. But the reverse for accepts_nested_attributess_for.

In my create controller for message, I included message.contacts.build

But right now I am still generating nil contacts.

Here is what I see passed as form data from google chrome:

message%5Baccount_name%5D:McKesson
message%5Btopic%5D:testing a contact
message%5Bbody%5D:testing this
sender_id:
receiver_id:23
message%5Bcontacts%5D%5Bemail%5D:[email protected]
message%5Bcontacts%5D%5Bfirst_name%5D:Ang
message%5Bcontacts%5D%5Blast_name%5D:Name
like image 499
Satchel Avatar asked Jul 08 '11 18:07

Satchel


2 Answers

The correct method name is simple_fields_for (notice the plural)

Also, you need to keep the f. to call it on the simple_form object

like image 199
axelarge Avatar answered Sep 27 '22 16:09

axelarge


I have a small project where I demonstrate how to use nested forms in simple-form, combined with cocoon (a gem I created to add/remove nested elements dynamically).

The project is on github.

Hope this helps.

like image 35
nathanvda Avatar answered Sep 27 '22 15:09

nathanvda