Rails3.2.8とRuby1.9.3を使用しています。
ネストされた属性の検証が実行されない理由、またはエラーが返される理由を理解するのに問題があります。何も入力せずにフォームを送信すると、親モデル(ユーザー)ではエラーが返されますが、子モデル(アカウント)ではエラーが返されません。
以下の私のコードでは、所有者が所有するアカウントモデル(アカウントモデル)と所有者に属するアカウントモデル(ユーザーモデル)があります。アカウントモデルには、サブドメイン文字列のテキストフィールドがあります。
サブドメインフィールドを含めずにフォームを送信すると、アカウントモデルの検証がまったく実行されないようです。ここで検証を機能させる方法についてのアイデアはありますか?ヘルプやポインタを事前に感謝します。
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