ruby-on-railsruby-on-rails-6form-for

Form to accept a record and multiple associated records?


If a user has_many skills, and a skill belongs_to a user:

class User < ApplicationRecord
  has_many :skills
  validates_length_of :skills, maximum: 5
end
class Skill < ApplicationRecord
  belongs_to :user
  validates_associated :user
end

how can a form be made that accepts the user and multiple skills?

Here is a form with the user and one skill, but I can't work out how to make it accept multiple skills in the same form?

<%= form_for(@user) do |f| %> 
  
  <%= f.label :bio %><br>
  <%= f.text_field :bio %>

   <%= fields_for "user[skill]", @user.skill do |skill_fields| %>
      <%= f.label :skill %><br>
      <%= skill_fields.text_field :name %>
   <% end %>

  <%= f.submit "Apply", class: "btn btn-primary" %>
<% end %>

Note, it's fine for the (5) fields to be on screen rather than generated dynamically with javascript.


Solution

  • accepts_nested_attributes_for

    You can consider using Rails built-in accepts_nested_attributes_for.

    Please, have a look at the Active Record Nested Attributes docs, especially in the One-to-many section.

    And this is the official guide on how to generate a Rails form for the accepts_nested_attributes_for - 10 Building Complex Forms.