Search code examples
ruby-on-railsassociationsform-forfields-for

Multiple text field in one fields_for


I'm building Project Management application and I'm creating Project with form_for but inside it I want a fields for to create 3 students.

I've set up my new.html.erb for Projects like this:

<h1>Creating new project</h1>

<%= form_for :project, url: projects_path do |f| %>
  <p>
    <%= f.label :name %>
    <%= f.text_field :name %>
  </p>

  <p>
    <%= f.label :lecturer %>
    <%= f.text_field :lecturer %>
  </p>

    <p>
        <%= f.fields_for :students do |s| %>
            <%= s.label :name %>
            <%= s.text_field :name %><br>
            <%= s.label :name %>
            <%= s.text_field :name %><br>
            <%= s.label :name %>
            <%= s.text_field :name %>
        <% end %>
    </p>

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

And for the create method jusst added one simple line to see my form_for result:

  def create
    render text: params[:project].inspect
  end

So when I fill up the text fields on page and hit submit all I get is {"name"=>"asd", "lecturer"=>"ffff", "students"=>{"name"=>"qeew"}} so as you can see only my last student was passed to this dictionary.

How can I create multiple students in one fields_for? Or how can I set up these two models to work with each other. I hope you get my point of view and know what I want to achieve.


Solution

  • You could build the number of students you need to have fields for in your controller new action like follows:

    # app/controllers/projects_controller.rb
    
    def new
      @project = Project.new
      3.times do 
        student = @project.students.build
      end
    end
    

    This will build three students under project instance.

    Then update your view's form_for declaration as follows:

    # app/views/projects/new.html.erb
    
    <%= form_for @project, url: projects_path do |f| %> 
      <p>
        <%= f.label :name %>
        <%= f.text_field :name %>
      </p>
      <p>
        <%= f.label :lecturer %>
        <%= f.text_field :lecturer %>
      </p>
      <p>
        <%= f.fields_for :students do |s| %>
          <%= s.label :name %>
          <%= s.text_field :name %>
        <% end %>
      </p>
      <p>
        <%= f.submit %>
      </p>
    <% end %>