首先,抱歉我的英语不好..
我在这里遇到了一些问题
我有来自视图表格的输出数据
{
code: 'code supplier',
name: 'name supplier',
address: 'address supplier',
phone_number: 'phone number supplier',
fax: 'fax supplier',
contact_persons: [
{name: 'contact person 1', value_number: '123456', value_type: 'mobile phone'},
{name: 'contact person 2', value_number: '123456', value_type: 'mobile phone'},
{name: 'contact person 3', value_number: '123456', value_type: 'email'},
{name: 'contact person 4', value_number: '123456', value_type: 'bb'}
]
bank_accounts: {
name: 'hendrik',
account_number: '1234578',
bank_name: 'bca',
branch_name: 'pasirkaliki'
}
}
我希望使用虚拟属性将它全部保存到关联的表中,我尝试了一些代码
#VIRTUAL ATTRIBUTES
attr_accessor :address, :phone_number, :fax, :contact_person, :bank_account, :value_number, :value_type, :bank_id, :account_name
# CALLBACKS
before_save :set_extra_attributes
def self.virtual_attributes
[:address, :phone_number, :fax, :bank_account, :contact_person, :value_number, :value_type, :bank_id, :account_name]
end
def set_extra_attributes
self.addresses = [Address.new(address: self.address)] if self.address.present?
self.phone_numbers = [PhoneNumber.new(number: self.phone_number, phone_type: 'phone')] if self.phone_number.present?
self.phone_numbers = [PhoneNumber.new(number: self.fax, phone_type: 'fax')] if self.fax.present?
self.bank_accounts = [BankAccount.new(account_number: self.bank_account, holding_company_id: '1', bank_id: self.bank_id.to_i, name: self.account_name)] if self.bank_account.present?
contact = [name: self.contact_person, value_type: self.value_type, value_number: self.value_number]
contact.each do |u|
ContactPerson.new(name: u[:name], value_type: u[:value_type], value_number: u[:value_number])
end
end
我使用Postgre, 我完全不确定上面的代码,因为它将每一列(例如self.value_type)设置为虚拟属性并且效率不高,任何方式只将bank_account和contact_person设置为虚拟属性和其他列(例如self.value_type)只是像contact_person [:value_type]那样设置哈希,我试过这个但仍然遇到一些问题,怎么做? 或者你们有另一种解决问题的好方法,我真的很感激,谢谢