【发布时间】:2018-01-21 00:25:56
【问题描述】:
在我的 ruby on rails 应用程序中,我在克隆模型后尝试保存模型时遇到问题。我有以下型号。
class Company < ApplicationRecord
has_many :employees
end
class Employee < ApplicationRecord
belongs_to :company
has_one :user
end
class User < ApplicationRecord
belongs_to :employee
end
当我使用以下代码时,我收到“ActiveRecord::RecordInvalid: Validation failed: Employee must exist”错误。
company = Company.new
employee = Employee.new(company: company)
user = User.new(name: 'John',email: 'example@gmail.com',password: 'password')
user.employee = employee
u = user.dup
u.save!
另一方面,当我使用“克隆”而不是“复制”时,Rails 会尝试保存用户模型两次,这会导致异常
company = Company.new
employee = Employee.new(company: company)
user = User.new(name: 'John',email: 'example@gmail.com',password: 'password')
user.employee = employee
u = user.clone
u.save!
如果我在不复制和克隆的情况下保存模型,则没有问题。在我的应用程序中,我使用的是构建器模式,并且必须使用 dup 或 clone 方法之一。
我看不到我错过了什么。
有什么建议吗?
谢谢。
【问题讨论】:
-
克隆模型的用例是什么?
-
确实,这似乎不是您的讲师或老板打算使用的构建器模式。我会仔细检查,因为在这种情况下重复没有明确的价值。
标签: ruby-on-rails ruby activerecord clone dup