1

当我保存申请模型时,它不会将嵌套模型数据保存到数据库中。我已经粘贴了我的控制器代码、模型代码和传递参数

我的参数是:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"5F8h7qG2pez9Rsutnq3JXYyXbPkbVJAlgfIfsE1bdUw=", "applicant"=>
{"job_id"=>"1", "first_name"=>"sanyam", "location"=>"", "email"=>"", "mob_no"=>"", "alternative_no"=>"", "last_name"=>"jain", "works_attributes"=>{"1366604495995"=>
{"title"=>"M Tech", "company_name"=>"", "start_month"=>"", "start_year"=>"", "end_month"=>"", "end_year"=>"", "description"=>"", "_destroy"=>"false"}, "1366604506595"=>
{"title"=>"B Tech", "company_name"=>"", "start_month"=>"", "start_year"=>"", "end_month"=>"", "end_year"=>"", "description"=>"", "_destroy"=>"false"}}, "linkedin"=>"", 
"twitter"=>"", "facebook"=>"", "message"=>""}, "submit"=>""}

我的控制器代码是:

def createProfile
@applicant = Applicant.new(params[:applicant])
@applicant.save
end

我的申请人模型是

class Applicant < ActiveRecord::Base
attr_accessible :first_name, :last_name, :location, :email, :mob_no, :alternative_no, :linkedin, :facebook, :twitter, :message, :resume, :job_id
has_many :works, :dependent => :destroy
has_many :educations, :dependent => :destroy
attr_accessible :works_attributes, :educations_attributes
accepts_nested_attributes_for :works, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

accepts_nested_attributes_for :educations, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

我的工作模式是

class Work < ActiveRecord::Base
attr_accessible :applicant_id, :company_name, :description, :end_month, :end_year, :start_month, :start_year, :title
belongs_to :applicant
validates_associated :applicant
end
4

2 回答 2

2

您指定的 reject_if 表示当参数中没有 :content 时,它不应该保存子模型。因此,请确保您的参数具有包含值的内容属性。你的参数应该看起来像这样:

{"utf8"=>"✓", "authenticity_token"=>"5F8h7qG2pez9Rsutnq3JXYyXbPkbVJAlgfIfsE1bdUw=", "applicant"=> {"job_id"=>"1", "first_name"=>"sanyam", "location"=>" ", "email"=>"", "mob_no"=>"", "alternative_no"=>"", "last_name"=>"jain", "works_attributes"=>{"1366604495995"=> {"title" =>"M Tech", "company_name"=>"", "start_month"=>"", "start_year"=>"", "end_month"=>"", "end_year"=>"", "description" =>"", "内容"=>"一些内容", "_destroy"=>"false"}, "1366604506595"=> {"title"=>"B Tech", "company_name"=>"", "start_month"=>"", "start_year"=>"", " end_month"=>"", "end_year"=>"", "description"=>"", "content"=>"一些内容", "_destroy"=>"false"}}, "linkedin"=>" ", "推特"=>"", "facebook"=>"", "消息"=>""}, "提交"=>""}start_year"=>"", "end_month"=>"", "end_year"=>"", "description"=>"", "content"=>"一些内容", "_destroy"=>"false"} }, "linkedin"=>"", "twitter"=>"", "facebook"=>"", "message"=>""}, "submit"=>""}start_year"=>"", "end_month"=>"", "end_year"=>"", "description"=>"", "content"=>"一些内容", "_destroy"=>"false"} }, "linkedin"=>"", "twitter"=>"", "facebook"=>"", "message"=>""}, "submit"=>""}=>“”}=>“”}

于 2013-04-22T09:29:19.390 回答
1

如果没有保存子表数据,请记住两个 attr_accessible

attr_accessible :first_name attr_accessible :works_attributes, :allow_destroy => true 接受_nested_attributes_for :works

于 2013-08-22T06:31:57.363 回答