leejay100
leejay100

Reputation: 221

Rails Create Multiple Records in Join Table

I'm trying to create multiple records in my join table via a create action. Here are my associations.

class User
  has_many :abilities
  has_many :skills, through: :abilities
end

class Job
  has_many :abilities
  has_many :skills, through: :abilities
end

class Ability
  belongs_to :job
  belongs_to :skill
end

I have a form to create a new Job. There is a select box to choose what skills are needed for the job (Skills are already created). In the create action of jobs_controller.rb, how do I create multiple Abilities? Here's what I have.

def create
  @job = Job.new(job_params)
  @abilities = @job.abilities.build(params[:job][:skills])
end

My params returns an array for skills.

"job"=> {
  "name"=>"abc",
  "skills"=>["2", "5"]
}

Getting stuck on how to create two Ability records in the create action of my jobs_controller (and associating the gig_id to the gig being created).

Upvotes: 4

Views: 1168

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

You can use the singular_collection_ids method for this:

#app/controllers/jobs_controller.rb
class JobsController < ApplicationController
   def new
      @job = Job.new
      @skills = Skill.all
   end

   def create
      @job = Job.new job_params
      @job.save
   end

   private

   def job_params
      params.require(:job).permit(skill_ids: [])
   end
end

#app/views/jobs/new.html.erb
<%= form_for @job do |f| %>
   <%= f.collection_select :skill_ids, @skills, :id, :name %>
   <%= f.submit %>
<% end %>

Having said this, you've got a major structural issue. You need to replace User with Skill:

#app/models/skill.rb
class Skill < ActiveRecord::Base
  has_many :abilities
  has_many :jobs, through: :abilities
end

#app/models/ability.rb
class Ability < ActiveRecord::Base
  belongs_to :job
  belongs_to :skill
end

#app/models/job.rb
class Job < ActiveRecord::Base
  has_many :abilities
  has_many :skills, through: :abilities
end

Upvotes: 1

edikgat
edikgat

Reputation: 869

the most simpliest way to do that is send from form "skill_ids"

"job"=> {
         "name"=>"abc",
         "skill_ids"=>["", "2", "5"]
         }

in controller

def create
  @job = Job.new(job_params)
  # ...
end

def job_params
  params.require(:job).permit([:name, skill_ids: []])
end

needed abilities will be created automatically

Upvotes: 1

Related Questions