我有一个接受用户模型嵌套属性的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.users.build的current_account对象创建。但我想确认一下。
发布于 2012-10-07 02:44:50
在用户模型中:
validates :account, :presence => true在帐户模型中:
has_many :users, :inverse_of => :account这只是验证父对象是否存在--即使它还没有被保存。
发布于 2012-10-07 02:17:56
我会考虑:
validates_presence_of :account_id, only => :create
validates_numericality_of_account_id:, :null => true # or :only => :create两种情况的分离和特殊帮助器的使用有助于立即可读性。
https://stackoverflow.com/questions/12762414
复制相似问题