【问题标题】:Rails validations are not being run on nested modelRails 验证未在嵌套模型上运行
【发布时间】:2012-08-29 15:48:36
【问题描述】:

我在 Rails 3.2.8 和 Ruby 1.9.3 上。

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

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

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

user.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

【问题讨论】:

    标签: ruby-on-rails ruby forms validation nested-attributes


    【解决方案1】:

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

    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 在子域属性为空时忽略嵌套帐户对象(参见cmets 中的讨论)

    【讨论】:

    • 感谢安德里亚。实际上,我把它放在我的帖子之外是一个错误。我进行了更新。我在我的用户模型中确实有它以及一个 :reject_if 语句来测试子域文本字段是否为空。但是,当我提交没有条目的表单并检查用户模型上的错误时,我没有得到任何自有帐户的信息,只有用户模型的错误。我也尝试过将owned_account 作为对象传递给fields_for,或者添加一个validates_presence_of,但是对于空的子域字符串我没有得到任何错误。有什么额外的想法吗?谢谢!
    • 嗨,您的 :reject_if 实际上导致嵌套帐户详细信息被完全忽略。您所拥有的基本上转换为“如果子域属性为空白,则拒绝嵌套帐户(不验证或保存)”。所以只需删除 :reject_if 位部分,您应该会看到验证。
    • 是的,你是对的,这就是问题所在。删除 reject_if 解决了这个问题。谢谢!
    • 嗨,我在表单中添加了嵌套属性,但没有 validates_associated ... 验证永远不会起作用,即使我删除了 reject_if,是否需要 validates_associated?
    【解决方案2】:

    看起来嵌套表单正在为owned_account_attributes 生成字段,这不是关联,而不是owned_account。 您是否尝试过在 Rails 控制台上使用嵌套属性执行 User.create 以查看它是否在那里工作?

    【讨论】:

    • 感谢您的回复。问题出在我的accept_nested_attributes_for 上的reject_if 语句。当子域字符串为空时,它拒绝嵌套模型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2011-06-10
    • 2012-12-12
    相关资源
    最近更新 更多