0

我有一个Account接受用户模型嵌套属性的模型。一个帐户has_many users。因此,没有帐户,用户就无法存在。我写了这个验证:

# users.rb
validates :account_id, presence: true, numericality: { only_integer: true }

在注册期间,用户填写帐户表单和嵌套用户表单。但是,由于该帐户尚不存在,因此我的测试因以下错误而失败:

#<ActiveModel::Errors: ... @base=#<Account id: nil, title: "ACME Corp", subdomain: "acme1", created_at: nil, updated_at: nil>, @messages={:"users.account_id"=>["can't be blank"]}>

我总是希望确保用户存在有效的帐户 ID,除非用户是通过Accounts#new. 换句话说,当Account同时创建一个帐户时,在这种情况下,还没有帐户 ID 可以提供给用户。

有没有办法做到这一点?

这可能是一个有争议的问题,因为所有新用户都将通过 current_account 对象 a la 创建current_account.users.build。但我想确定。

4

2 回答 2

1

在用户模型中:

validates :account, :presence => true

在帐户模型中:

has_many :users, :inverse_of => :account

这只是验证父对象是否存在 - 即使它尚未保存。

于 2012-10-06T18:44:49.873 回答
0

我会考虑:

validates_presence_of :account_id, only => :create
validates_numericality_of_account_id:, :null => true # or :only => :create

两种情况的分离和特殊助手的使用有助于立即阅读。

于 2012-10-06T18:17:55.573 回答