Rails validations are not being run on nested model

自闭症网瘾萝莉.ら 提交于 2020-01-02 08:58:07

问题


I'm on Rails 3.2.8 and Ruby 1.9.3.

I'm having trouble figuring out why the validations on the nested attributes are not being run or returning any errors. When I submit the form with nothing filled in, I get errors back for the parent model (User), but not for the child model (Account).

In my code below, I have a User model which has_one owned_account (Account model), and an Account model that belongs_to an owner (User model). The Account model has a text field for a subdomain string.

It seems that when I submit the form without including the subdomain field, the validations on the Account model are not run at all. Any ideas on how I can get the validations here working? Thanks in advance for any help or pointers.

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

回答1:


You need to add the accepts_nested_attributes_for method to the User model. Like so:

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

Then you should see validation errors pertaining to the nested model on the parent model (User):

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

EDIT

The culprit turned out to be the :reject_if bit in the accepts_nested_attributes_for line that effectively instructed Rails to ignore nested account objects if the subdomain attribute was blank (see discussion in comments)




回答2:


It looks like the nested form is generating fields for owned_account_attributes, which is not an association, instead of owned_account. Have you tried doing a User.create with nested attributes on the rails console to see if it works there?



来源:https://stackoverflow.com/questions/12272727/rails-validations-are-not-being-run-on-nested-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!