user1647525
user1647525

Reputation: 321

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

Upvotes: 4

Views: 5370

Answers (2)

Andrea Singh
Andrea Singh

Reputation: 1613

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)

Upvotes: 5

Ari
Ari

Reputation: 2378

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?

Upvotes: 0

Related Questions