简体   繁体   English

如何验证其他Rails表中的字段?

[英]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.. 我的表格是一个form_tag顺便说一句,由于种种原因我无法更改它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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