i'm trying create multiple records in join table via create action. here 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 form create new job. there select box choose skills needed job (skills created). in create action of jobs_controller.rb, how create multiple abilities? here's have.
def create @job = job.new(job_params) @abilities = @job.abilities.build(params[:job][:skills]) end
my params returns array skills.
"job"=> { "name"=>"abc", "skills"=>["2", "5"] }
getting stuck on how create 2 ability records in create action of jobs_controller (and associating gig_id gig being created).
you can use singular_collection_ids
method 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 |f| %> <%= f.collection_select :skill_ids, @skills, :id, :name %> <%= f.submit %> <% end %>
having said this, you've got major structural issue. need replace user
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
Comments
Post a Comment