gpt4 book ai didi

ruby-on-rails - Rails 验证未在嵌套模型上运行

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:50 26 4
gpt4 key购买 nike

我正在使用 Rails 3.2.8 和 Ruby 1.9.3。

我无法弄清楚为什么对嵌套属性的验证没有运行或返回任何错误。当我提交未填写任何内容的表单时,我会返回父模型(用户)的错误,但不会返回子模型(帐户)的错误。

在我下面的代码中,我有一个拥有一个拥有帐户的用户模型(帐户模型)和一个属于所有者的帐户模型(用户模型)。 Account 模型有一个用于子域字符串的文本字段。

似乎当我提交不包含子域字段的表单时,帐户模型上的验证根本没有运行。关于如何在此处进行验证的任何想法?在此先感谢您的帮助或指点。

用户.rb

class User < ActiveRecord::Base
attr_accessible :owned_account_attributes
has_one :owned_account, :class_name => 'Account', :foreign_key => 'owner_id'

validates_associated :owned_account
accepts_nested_attributes_for :owned_account, :reject_if => proc { |attributes| attributes['subdomain'].blank? }
end

account.rb

class Account < ActiveRecord::Base
attr_accessible :owner_id, :subdomain
belongs_to :owner, :class_name => 'User'

validates :subdomain,
:presence => true,
:uniqueness => true,
:format => { ...some code... }
end

new.haml

= form_for @user do |f|
... User related fields ...
= f.fields_for :owned_account_attributes do |acct|
= acct.label :subdomain
= acct.text_field :subdomain
= submit_tag ...

users_controller.rb

class UsersController < ApplicationController
def new
@user = User.new
end

def create
@user = User.new(params[:user])

if @user.save
...
end
end

最佳答案

您需要将 accepts_nested_attributes_for 方法添加到 User 模型。像这样:

class User < ActiveRecord::Base
attr_accessible :owned_account_attributes, # other user attributes
has_one :owned_account, :class_name => 'Account', :foreign_key => 'owner_id'

accepts_nested_attributes_for :owned_account
validates_associated :owned_account
end

然后您应该看到与父模型(用户)上的嵌套模型有关的验证错误:

["Owned account subdomain can't be blank", "Owned account is invalid"]

编辑

罪魁祸首原来是 accepts_nested_attributes_for 行中的 :reject_if 位,它有效地指示 Rails 在子域属性为空时忽略嵌套的帐户对象(请参阅讨论评论)

关于ruby-on-rails - Rails 验证未在嵌套模型上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com