如何在 rails 中复制另一个模型的属性?

How to copy a attribute of another model in rails?

我尝试在创建后使用 User 复制 email 属性,但在日志中出现错误。

我尝试的方法是:

class Car < ActiveRecord::Base
  belongs_to :user
  attr_accessible  :email, :engine

  after_create :get_email

  def get_email
    email = user.email.dup
  end
end

有人可以给点提示吗?

您的代码中缺少两件事:

    需要
  1. self 来设置 email 的值。
  2. 对象设置后需要保存email

因此,在添加 selfsave 之后,您的 get_email 方法应该如下所示:

def get_email
  self.email = user.email
  save
end

请注意,dup 也已被删除,因为不需要复制该值(有关 dup here 的更多信息)。


也就是说,我建议使用 before_create 操作而不是 after_create:

class Car < ActiveRecord::Base
  belongs_to :user
  attr_accessible  :email, :engine

  before_create :get_email

  def get_email
    self.email = user.email
  end
end

使用 :before_crete,您将从 User 复制 email,并且只需要保存您的对象一次。如果使用 :after_create 执行此操作,首先您将保存对象,然后在 User 中查找 email,然后需要执行额外的 update(即再次保存).