0

Ok so i have a Contact model

class Contact < ActiveRecord::Base
  has_one :profile
  validates_presence_of :first_name
  validates_presence_of :last_name
  validates_presence_of :email

class Profile < ActiveRecord::Base
   belongs_to :contact

And on my form i have fields from that profile and the contact and the validations for the contacts show up but i want to validate the fields from profile. I assumed that adding this to the controller would add to the error messages.

    @contact.errors.add(:base, "Profile Company cant be blank")

ANy ideas

My form is a form_tag BTW and i cant change that for various reasons..

Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321

2 Answers2

0

If you want to check the validity of associated records when saving the owning record:

   class Contact
        validates_associated :profile
JohnMerlino
  • 3,900
  • 4
  • 57
  • 89
  • but i dont want to validate on every record...just when the profile in the params....is that possible – Matt Elhotiby Jul 31 '12 at 23:40
  • You can extend ActiveModel::EachValidator, which passes the current record and you can check if an attribute is set on the record from the form. Something like on this answer: http://stackoverflow.com/questions/7387459/validates-associated-with-models-error-message – JohnMerlino Jul 31 '12 at 23:48
0

I am not sure if this will work

class Contack < ActiveRecord::Base
  validates_associated :profile,
    :if => Proc.new { |a| a.profile.present? }
end
az7ar
  • 5,187
  • 2
  • 19
  • 23