我有一个模型作业。一份工作需要很多技能。但是当我试图挽救我的工作时就失败了。我不确定我明白我做错了什么。 我的模型:Rails 4,嵌套保存属性
class Skill < ActiveRecord::Base
has_many :job_skills
has_many :jobs, through: :job_skills
end
class JobSkill < ActiveRecord::Base
belongs_to :skill
belongs_to :job
end
class Job < ActiveRecord::Base
has_many :job_skills, :inverse_of => :job
has_many :skills, through: :job_skills
accepts_nested_attributes_for :job_skills
end
我的观点:
<%= form_for @job do |f| %>
<div class="row">
<div class="col-md-8">
<h4>General informations</h4>
<br />
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, :autofocus => true, class:'form-control' %>
</div><br />
<%= f.fields_for :job_skills do |s| %>
<%= s.text_field :id %>
<% end %>
</div>
</div>
<div class="submit" style="position:relative;">
<%= f.submit "Save", class: 'button button-small' %>
</div>
<% end %>
我的控制器:
class JobsController < ApplicationController
before_filter :authenticate_user!, :has_company?, :except => [:index, :show]
def create
@job = Job.new(job_params)
@job.company_id = current_user.company_id
@job.user_id = current_user.id
if @job.save
flash[:notice] = "This job offer has been saved."
return redirect_to job_path(@job)
else
flash[:error] = @job.errors.full_messages.to_sentence
render action: :new
end
end
def new
if current_user.company.present?
@job = Job.new(email:current_user.email)
@job.job_skill.build
else
flash[:error] = "You need to create a company before posting a job"
return redirect_to new_company_path()
end
end
private
def job_params
params.require(:job).permit(:status, :title, :description, :remote ,:job_type, :visa_sponsor, :email, :salary_max, :salary_min, :country, :state, :city, job_skill_attributes: [:id])
end
end
所以,我不知道我在做什么错了,当我试图为了节省我得到以下错误:
@job = Job.new(job_params)
ActiveRecord::RecordNotFound Exception:
Couldn't find Skill with ID=4 for Job with ID= nil
大概dubplicate的[Rails的:多级嵌套表格(接受嵌套属性)] [1] [1]:http://stackoverflow.com/q/23952099/1065703 – 2014-10-12 09:23:56
@MartinM呜呜,创建后无法工作,因为问题发生在Job.new() – bl0b 2014-10-12 09:58:43
不应该是'has_many:job_skills'在第一个模型中,而不是''has_many:jobskills'? – GMA 2014-10-12 10:10:27