Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validations are not being run on nested model

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
like image 448
user1647525 Avatar asked Nov 06 '25 18:11

user1647525


1 Answers

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)

like image 186
Andrea Singh Avatar answered Nov 09 '25 14:11

Andrea Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!