Railsvalidation未在嵌套模型上运行
我在Rails 3.2.8和Ruby 1.9.3上。
我无法弄清楚为什么没有运行嵌套属性的validation或返回任何错误。 当我提交没有填写任何内容的表单时,我会为父模型(用户)收到错误,但不会为子模型(帐户)收到错误。
在我的下面的代码中,我有一个用户模型has_one owned_account(帐户模型),以及一个属于所有者的帐户模型(用户模型)。 Account模型具有子域字符串的文本字段。
看来,当我提交表单而不包含子域字段时,帐户模型上的validation根本不会运行。 关于如何在此处获得validation的任何想法? 提前感谢任何帮助或指示。
user.rb
class User '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 '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
然后,您应该看到与父模型(User)上的嵌套模型有关的validation错误:
["Owned account subdomain can't be blank", "Owned account is invalid"]
编辑
罪魁祸首原来是:reject_if
行中的:reject_if
位,如果子域属性为空,则有效指示Rails忽略嵌套帐户对象(请参阅注释中的讨论)
看起来嵌套表单为owned_account_attributes生成字段,而不是关联,而不是owned_account。 您是否尝试在rails控制台上使用嵌套属性执行User.create以查看它是否在那里工作?