【问题标题】:Save params value in before_save callback在 before_save 回调中保存参数值
【发布时间】:2015-06-08 12:54:40
【问题描述】:

你好,我的参数里有这个

参数:{"utf8"=>"✓", "authenticity_token"=>"YmYvS/vPVB9FD7+XvDx0+K8UKHReHLifTmc91xD8pASSNqg9d0b/77NnodxQYhbN806661eSBk9vQwTHib3w/w==", "employee"=>{"profile_attributes"=>{"name"=>"dinshaw", "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", "role"=>"SUPER-ADMIN", "department_id"=>"1", "designation_id"=>"1", "is_active"=>"1", "contact_attributes"=>{"phone_no"=>"9856321470", "current_address1"=>"test1dinsh", "current_address2"=>"awwwwwwwww", "country"=>"IN", "city"=>"Indore", "zip"=>"452001", "emergency_contact_person"=>"abhi", "emergency_contact_no"=>"9632145870", "relation"=>"farji"}, "permanent_address_attributes"=>{"address1"=>"testbghghgjh", "address2"=>"hdvhdkhfdhnbdfds", "country"=>"IN", "city"=>"Ghaziabad", "zip"=>"12356"}}, "联系人"=>{"state_code"=>"MP"}, "permanent_address"=>{"state_code"=>"CH"}, "commit"=>"更新 员工", "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] 

我不知道如何在模型中获取它。请指导我。提前致谢

【问题讨论】:

    标签: ruby-on-rails model


    【解决方案1】:
    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] 
    

    【讨论】:

    • 如果您不向模型发送任何内容,那么该值将如何通过模型保存..?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    相关资源
    最近更新 更多