Forum: Ruby on Rails conditional model validation

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C22c46a54673d3f35910b1a4199ee80f?d=identicon&s=25 jzimmek (Guest)
on 2009-03-23 21:27
(Received via mailing list)
i really like the declarative model-based validation in rails, but i
run into trouble while doing some real world (more complex) stuff.

class User < ActiveRecord::Base
  belongs_to :address
  accepts_nested_attributes_for :address
  def needs_street_validation?
    true
  end
end

class Address < ActiveRecord::Base
  has_one :user
  validates_presence_of :street, :if => Proc.new { |adr|
 adr.user.needs_street_validation? }
end

u = User.new
u.address = Address.new
u.save

NoMethodError: You have a nil object when you didn't expect it!
The error occurred while evaluating nil.needs_street_validation?
        from app/models/address.rb:3


seems to me like we cannot reference any associated object within the
":if" condition or do you know some trick to get this working ?

maybe this is not the best example, but i hope you got the point.

in most more-complex gui's we have conditional validation based on the
state of multiple objects. It would be a shame if we could only handle
those validation programmatically.

tested in a vanilla rails 2.3.2 application.

any help would be really appreciated.

regards
jan
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-03-23 22:19
(Received via mailing list)
On Mar 23, 8:26 pm, jzimmek <jan.zim...@web.de> wrote:
> ":if" condition or do you know some trick to get this working ?
>
The problem isn't anything to do with :if's, more a general quirk of
activerecord - When you assign Address.new to u.address activerecord
doesn't update the inverse assocation on the address object. In the
case where you're doing this with already saved objects you can use
tricks like set_#{association_name}_target to do that work of filling
in the inverse association, though I don't know if  the fact that your
objects are unsaved makes a difference.


Fred
This topic is locked and can not be replied to.