Rails validations are not being run on nested model

旧城冷巷雨未停 提交于 2019-12-05 23:27:37

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)

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?

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