我有工作模式,技术模式和job_skill模型如何将数据保存到has_many_through表,同时节省与nested_form轨父对象
class Job < ActiveRecord::Base
has_many :job_skills
has_many :skills ,through: :job_skills
accepts_nested_attributes_for :job_skills
class Skill < ActiveRecord::Base
has_many :job_skills
has_many :jobs ,through: :job_skills
accepts_nested_attributes_for :job_skills
class JobSkill < ActiveRecord::Base
belongs_to :skill
belongs_to :job
accepts_nested_attributes_for :job
accepts_nested_attributes_for :skill
和就业控制器
class JobsController < ApplicationController
def new
@job = Job.new
@job.job_skills.build
end
def create
@job = Job.new(job_params)
@job.save
end
private
def job_params
params.require(:job).permit(:occupation, :industry, :location,job_skills_attributes:[])
end
和工作形式是
= form_for @job do |f|
= f.label :location
= f.text_field :location
.clear
= f.label "industry*"
= f.text_field :industry
.clear
= f.label :occupation
= f.text_field :occupation
.clear
= f.label "Skill Required*"
= f.fields_for(:job_skills) do |s|
= s.select :skill_id, Skill.all.collect{|p| [p.skill, p.id]},{}, {:multiple => true, :class=> "chosen-select multiple-select-skills"}
= f.submit "submit"
only job get save。 jobs_skills不保存。在工作参数中,我只能得到工作数据。可能是什么原因。请帮忙。!!您的form_for到nested_form_for
= nested_form_for @job do |f|
= f.label :location
= f.text_field :location
.clear
= f.label "industry*"
= f.text_field :industry
.clear
= f.label :occupation
= f.text_field :occupation
.clear
= f.label "Skill Required*"
= f.fields_for(:job_skills) do |s|
= s.select :skill_id, Skill.all.collect{|p| [p.skill, p.id]},{}, {:multiple => true, :class=> "chosen-select multiple-select-skills"}
虽然保存工作job_skill必须自动保存,但它不会发生 – user3779329
你必须使用nested_form_for而不是form_for。 – user100693
nested_form_for是未定义的方法。 ..你的意思是我必须使用nested_form gem.right? – user3779329