在before_save回调中保存params值

时间:2015-06-08 12:54:40

标签: ruby-on-rails model

你好,我在我的参数中得到了这个

  

参数:{" utf8" =>"✓",   " authenticity_token" =>" YmYvS / vPVB9FD7 + XvDx0 + K8UKHReHLifTmc91xD8pASSNqg9d0b / 77NnodxQYhbN806661eSBk9vQwTHib3w / w ==","员工" => {" profile_attributes& #34; = GT; {"名称" = GT;" dinshaw&#34 ;,   " date_of_joining" =>" 2015年6月8日"," date_of_birth" =>" 2015年6月2日",   " aniversary" =>" 2015年6月3日"," last_position" =>"开发者",   " passport_no" =>" AK972345"," passport_expiry_date" =>" 2015年6月27日",   " pan_no" =>" BHJ47"}," email" =>" draje@adroit-inc.com",   "角色" =>" SUPER-ADMIN"," department_id" =>" 1"," designation_id" =>" 1&#34 ;,   " is_active" =>" 1"," contact_attributes" => {" phone_no" =>" 9856321470&#34 ;,   " current_address1" =>" test1dinsh"," current_address2" =>" awwwwwwwww",   " country" =>" IN"," city" =>" Indore"," zip" => ;" 452001&#34 ;,   " emergency_contact_person" = GT;" ABHI&#34 ;,   " emergency_contact_no" =>" 9632145870","关系" =>" farji"},   " permanent_address_attributes" = GT; {"地址1" = GT;" testbghghgjh&#34 ;,   "地址2" =>" hdvhdkhfdhnbdfds"," country" =>" IN"," city" => ;" Ghaziabad的&#34 ;,   " zip" =>" 12356"}},"联系" => {" state_code" =>" MP& #34;},   " permanent_address" => {" state_code" =>" CH"},"提交" =>"更新   员工"," id" =>" 1"}

现在在我的employee.rb中,我已经包含了这段代码

class Employee < ActiveRecord::Base
  belongs_to :department
  belongs_to :designation
  has_one :profile
  has_one :contact
  has_one :permanent_address
  has_many :attachments, as: :attachable
  accepts_nested_attributes_for :attachments
  accepts_nested_attributes_for :profile, :contact, :permanent_address
  before_save :set_state_code

  def set_state_code
    self.contact.state_code = 'AP'
    self.permanent_address.state_code = 'MP'
  end

  def create_association_instance
    self.build_profile unless self.profile
    self.build_contact unless self.contact
    self.build_permanent_address unless self.permanent_address
    self.attachments.build unless self.attachments.present?
  end

end

但我想要

self.contact.state_code = params[:contact][:state_code] && 
self.permanent_address.state_code = params[:permanent_address][:state_code] 

我没有得到如何在模型中获取它。请指导我。提前致谢

1 个答案:

答案 0 :(得分:0)

class Employee < ActiveRecord::Base
  attr_accessor :contact_state_code, :address_state_code
  before_save :set_state_code

  def set_state_code
    self.contact.update_column(state_code: self.contact_state_code)
    self.permanent_address.update_column(state_code: self.address_state_code)
  end
end

并在控制器中执行以下操作:

params[:employee][:contact_state_code] = params[:contact][:state_code]
params[:employee][:address_state_code] = params[:permanent_address][:state_code]