【问题标题】:deleting attributes from ActiveRecord model从 ActiveRecord 模型中删除属性
【发布时间】:2011-03-01 17:27:35
【问题描述】:

我正在两个 activerecord 连接之间迁移数据,我的模型都设置正确,所以我可以读取 Legacy::Tablename 和 Tablename 并将其插入到新表中。

我遇到的问题是我的新模型没有旧模型中的所有属性,因此当我尝试通过以下方式在新模型中创建记录时,我得到一个“未知属性”;

legacy_users = Legacy::User.all
legacy_users.each do |legacy_user|
  User.create legacy_user.attributes
end

但是,如果我尝试删除有问题的属性,它仍然不起作用,例如。

legacy_user.attributes.delete 'some_attribute'

谁能指点一下?

【问题讨论】:

  • 您必须使用 ActiveRecord,还是可以使用普通的旧 SQL 代替?直接从数据库转储/加载数据比实例化、验证和保存 ActiveRecord 对象要快得多。

标签: ruby-on-rails ruby


【解决方案1】:

attributes.except(:some_attribute) 怎么样?

【讨论】:

  • 在 rails 4 上应该是:attributes.except('some_attribute')
  • Rails Hash#except 有效,attributes 返回哈希值。
【解决方案2】:

这应该在这种情况下工作:

legacy_users = Legacy::User.all
legacy_users.each do |legacy_user|
  u = User.new

  u.attributes.each do |k, v|
    old_val = legacy_user.send(k) # Get the attr from old user
    u.send("#{k}=", old_val) # Set it to the new user
  end
end

您也不需要经历删除每个未使用属性的麻烦

【讨论】:

  • 返回 'NameError: method `some_attribute' not defined in Legacy::User'
  • 我发布了另一个回复!
  • 是的,效果很好 - 这将是您的答案和 Deepaks 的组合,因为有时属性在旧模型中,而新模型中没有,反之亦然。
【解决方案3】:

我也在进行迁移,就我而言,我将一个块传递给first_or_create 以克隆对象。我无法让 delete()except() 工作,但由于某种原因,它可以工作:

scrubbed_obj = my_obj.attributes.reject { |k,v| k == 'the_attribute_you_dont_want' }

new_object.attributes = scrubbed_obj

然后该块保存良好。如果其他人遇到类似问题,请在此处放弃此答案。

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 2011-12-26
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多