ruby-on-rails – 重新分配ActiveRecord实例和相应的外键
发布时间:2020-12-17 02:00:07 所属栏目:百科 来源:网络整理
导读:在Rails / ActiveReocrd中有一种方法可以将一个实例替换为另一个实例,以便解决所有关系/外键. 我可以想象这样的事情: //setupcustomer1 = Customer.find(1)customer2 = Customer.find(2)//this would be coolcustomer1.replace_with(customer2) 假设custome
在Rails / ActiveReocrd中有一种方法可以将一个实例替换为另一个实例,以便解决所有关系/外键.
我可以想象这样的事情: //setup customer1 = Customer.find(1) customer2 = Customer.find(2) //this would be cool customer1.replace_with(customer2) 假设customer1配置错误并且有人已经离开并创建了customer2,而不知道customer1那么能够快速将所有内容设置为客户2会很好 所以,这也需要更新任何外键 用户belongs_to:客户 然后任何具有外键customer_id = 1的用户/网站将通过此’replace_with’方法自动设置为2 这样的事情存在吗? [我可以想象一个涉及Customer.reflect_on_all_associations(:has_many)等的黑客攻击] 干杯, 解决方法
像这样的东西可以工作,虽然可能有更合适的方式:
更新:更正了关联示例中的一些错误. class MyModel < ActiveRecord::Base ... # if needed,force logout / expire session in controller beforehand. def replace_with (another_record) # handles attributes and belongs_to associations attribute_hash = another_record.attributes attribute_hash.delete('id') self.update_attributes!(attribute_hash) ### Begin association example,not complete. # generic way of finding model constants find_model_proc = Proc.new{ |x| x.to_s.singularize.camelize.constantize } model_constant = find_model_proc.call(self.class.name) # handle :has_one,:has_many associations have_ones = model_constant.reflect_on_all_associations(:has_one).find_all{|i| !i.options.include?(:through)} have_manys = model_constant.reflect_on_all_associations(:has_many).find_all{|i| !i.options.include?(:through)} update_assoc_proc = Proc.new do |assoc,associated_record,id| primary_key = assoc.primary_key_name.to_sym attribs = associated_record.attributes attribs[primary_key] = self.id associated_record.update_attributes!(attribs) end have_ones.each do |assoc| associated_record = self.send(assoc.name) unless associated_record.nil? update_assoc_proc.call(assoc,self.id) end end have_manys.each do |assoc| associated_records = self.send(assoc.name) associated_records.each do |associated_record| update_assoc_proc.call(assoc,self.id) end end ### End association example,not complete. # and if desired.. # do not call :destroy if you have any associations set with :dependents => :destroy another_record.destroy end ... end 我已经列举了一个如何处理一些关联的例子,但总的来说这可能变得棘手. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |