首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >accepts_nested_attributes和验证的边缘案例

accepts_nested_attributes和验证的边缘案例
EN

Stack Overflow用户
提问于 2012-10-07 02:06:25
回答 2查看 86关注 0票数 0

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

代码语言:javascript
复制
# users.rb
validates :account_id, presence: true, numericality: { only_integer: true }

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

代码语言:javascript
复制
#<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对象创建。但我想确认一下。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-07 02:44:50

在用户模型中:

代码语言:javascript
复制
validates :account, :presence => true

在帐户模型中:

代码语言:javascript
复制
has_many :users, :inverse_of => :account

这只是验证父对象是否存在--即使它还没有被保存。

票数 1
EN

Stack Overflow用户

发布于 2012-10-07 02:17:56

我会考虑:

代码语言:javascript
复制
validates_presence_of :account_id, only => :create
validates_numericality_of_account_id:, :null => true # or :only => :create

两种情况的分离和特殊帮助器的使用有助于立即可读性。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12762414

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档