【问题标题】:Ruby copying between active model objects活动模型对象之间的 Ruby 复制
【发布时间】:2013-11-16 11:52:23
【问题描述】:

只需尝试找出如何将属性从一个活动模型复制到另一个,而不必一个一个地进行。

我有两个模型,一个是 RFM(ruby to filemaker),一个是 mongoid,两个都是 mixin 活动模型。

gem "ginjo-rfm"

模型

require 'rfm'

class StudentAdmin < Rfm::Base
  config :layout => 'STUDENT_ADMIN_LAYOUT'
  attr_accessor :name_first,:name_last
end

Mongoid 模型

class Student
  include Mongoid::Document

  field :first_name, type: String
  field :last_name, type: String
end

我可以快速复制吗?我在活动记录对象之间找到了一个示例,例如

 student_admin = ... #load StudentAdmin
 Student.new(student_admin.attributes.slice(Student.attribute_names))

但 RFM 不提供属性方法。

编辑

对不起,我想要达到的效果比这更好

student_admins = #get student admins from external service
students = []
student_admins.each() do |sa|
students.push(Student.create!(first_name: sa.name_first, last_name: sa.name_last)) 
end

这个例子只显示了 2 个属性,但实际上有超过 50 个,并且想知道是否有一种方法可以做到这一点而不必指定每个属性,例如如果两个对象的属性名称相同,则自动复制它们。

【问题讨论】:

  • 您只是想将每个StudentAdmin 记录迁移到相应的Student 记录吗?

标签: ruby-on-rails


【解决方案1】:

试试这个:

students = student_admins.map do |sa|
  attrs = sa.methods.inject({}) do |hash, m|
    next unless Student.column_names.include? m.to_s
    hash[m] = sa.send m
  end
  Student.create(attrs)
end

Student 必须是继承自 ActiveRecord::Base 的类:

class Student < ActiveRecord::Base
  ...
end

【讨论】:

  • 对不起,这不是我的意思,我已经编辑了我的问题
  • 我现在明白了。更改了我的答案,让我知道它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 2018-02-25
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多