开发者

reverse validates_associated

i am trying to validate a field depending on attributes from the associated model. looking at the code will make more sense (i hope)

class User < ActiveRecord::Base
  has_and_belongs_to_many :user_groups
  has_one :profile, :dependent => :destroy

  accepts_nested_attributes_for :profile
  validates_associated \
    :profile,
    :allow_destroy => true
end


class Profile < ActiveRecord::Base
  belongs_to  :user

  validates_presence_of \
    :business_name,
    :if => self.user.user_groups.first.name == 'Client'
end

when i submit the form to create a new user, i get

undefined method `user_groups' for nil:NilClass

basically i only want to validate the presence of the field business_name if i am creating a new client.

i h开发者_运维问答ave also tried using

:if => Proc.new { |p| p.user.user_groups.first.name == 'Clients' }

with the same results.

maybe i am barking up entirely the wrong tree, but any suggestions on accomplishing this?


You have a belongs_to association which takes user_id and finds the User object with that ID. However, your Profile model is being validated before your User is saved, so it has no ID. Your validation in Profile can't call into the User yet in this case.

You need to detangle this logic so it's triggered in the User or in the Profile, but the Profile can't expect a created user to do it's own validation if you want to validate the Profile first.

This is a chicken and egg problem.

You can fix this by adding a column like is_business to Profile and changing your code as follows:

class Profile < ActiveRecord::Base
  belongs_to  :user

  validates_presence_of \
    :business_name,
    :if => is_business?
end

and update your Profile form to set is_business correctly in the context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜