Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: submitting a form with multiple objects

I'm creating a Rails application, and I've hit a bit of a snag. I want a "create new record for DataType1" form that not only creates a new row for DataType1, but also inserts up to four new rows for DataType2.

I know all about fields_for, but my problem is that I need to submit up to four DataType2s, and the only connection they have to DataType1 is that they are referenced via a field in DataType2.

Here's the simplified database:

create_table :data_type_1 do |t|
  t.string     :title
  t.text       :body

  t.timestamps
end

create_table :data_type_2 do |t|
  t.belongs_to :parent

  t.timestamps
end

Now, I have the relationships all set up and everything; that's not the problem. The problem is that I just can't seem to figure out how to pass the params for the DataType2s in with the params for the new DataType1. Once someone shows me how I should go about doing this, I can set up the new DataType2s to associate with the new DataType1 fairly easily.

Here's what I have for the form at the moment:

<% form_for(@data_type_1) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>

  # Etc...

  <p>
    # New items need to be iterated here
    # DataType2[1]: [         ]
    # DataType2[2]: [         ]
    # DataType2[3]: [         ]
    # DataType2[4]: [         ]
    # (Note that these numbers are just examples.)
  </p>

  <p>
    <%= f.submit "Create" %>
  </p>
<% end %>

I'm relatively new to Rails, and I apologize if this question rambles a bit.

like image 520
Adam Rezich Avatar asked Dec 13 '22 05:12

Adam Rezich


1 Answers

This RailsCast talks about inserting lists of "DataType2" into "DataType1". The interesting parts are these

app/views/projects/_form.html.erb

  <% for task in @project.tasks %>
    <% fields_for "project[task_attributes][]", task do |task_form| %>
      <p>
        Task: <%= task_form.text_field :name %>
      </p>
    <% end %>
  <% end %>

app/models/project.rb

def task_attributes=(task_attributes)
  task_attributes.each do |attributes|
    tasks.build(attributes)
  end
end
like image 64
Bill Avatar answered Dec 26 '22 11:12

Bill