我正在尝试在rails中编写自定义验证,以检查我输入的值是否在数据库中是重复的。
我需要检查的值基于4个不同的表/模型
我正在尝试写这样的东西进行验证:
class Locations::BranchBusinessGroup < Locations::Database
validate :url_duplicated
private
def url_duplicated
if self.location.url_prefix.valid?
errors.add(:location, 'URL is take')
else
if self.custom_url.valid? && self.self.business_group.is_on_web #both in different models
errors.add(:location, 'URL is used in a custom URL')
end
end
end
url_prefix
,url_suffix
,':custom_url',is_on_the_web
是表单输入的所有字段。逻辑应该检查url_prefix
和url_suffix
是否已经输入,如果它们不匹配':custom_url'和is_on_the_web
。
痴迷这不是编码这个及其超级错误的正确方法。它只是我想如何检查验证的想法。任何光线都会很好。
我得到的错误是: undefined method
有效? for“chantilly-va”:String`
答案 0 :(得分:0)
我不清楚Location
和BusinessGroup
到底是什么,但总的想法是这样的:
def url_duplicated
if self.class.where(url_prefix: url_prefix).where.not(id: id).exists?
errors.add(:location, 'URL is taken')
elsif self.class.where(custom_url: custom_url, is_on_web: true).where.not(id: id).exists?
errors.add(:location, 'URL is used in a custom URL')
end
end
基本上,您希望进行查找以查找是否存在与这些术语匹配的记录(并且没有记录自己的id
)。注意,where.not(...)
语法只能从Rails 4开始。