在rails模型中,可以这样做吗?
class Example < ActiveRecord::Base
#associations
validates_presence_of :item_id, (:user_id OR :user_email)
#functions
end其中模型有3列:item_id、:user_id和:user_email?只要我有:user_id或:user_email,我就希望模型有效。
想法是,如果该项目是推荐给一个人谁是目前没有注册,它可以通过电子邮件地址相关联的时候,推荐的人注册。
或者有没有不同的方法可以代替呢?
发布于 2010-06-03 10:29:16
一种方法是将这些字段包装为虚拟属性,例如:
class Example < ActiveRecord::Base
validates_presence_of :referral
def referral
user_id || user_email
end
end或者,您可以直接抛出一个自定义的validate验证方法。查看Rails API上的自定义验证
如果user_id和user_email都来自另一个模型,那么添加关联可能更好
class Example
belongs_to :user
validates_associated :user
before_validate :build_user_from_id_or_email
def build_user_from_id_or_email
# ... Find something with the parameters
end
end发布于 2010-06-03 10:33:46
validates_presence_of :item_id
validates_presence_of :user_id, :if => Proc.new{ |x| x.user_email.blank? }
validates_presence_of :user_email, :if => Proc.new{ |x| x.user_id.blank? }https://stackoverflow.com/questions/2962921
复制相似问题