简体   繁体   中英

How do i validate fields in the other rails table?

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..

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

   class Contact
        validates_associated :profile

I am not sure if this will work

class Contack < ActiveRecord::Base
  validates_associated :profile,
    :if => Proc.new { |a| a.profile.present? }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM