views:

24

answers:

2

In a rails model, is it possible to do something like

class Example < ActiveRecord::Base
  #associations  

  validates_presence_of :item_id, (:user_id OR :user_email)

  #functions
end

Where the model has 3 columns of :item_id, :user_id, and :user_email? I want the model to be valid as long as I have a :user_id or a :user_email.

Idea being that if the item is recommended to a person who isn't currently signed up, it can be associated via email address for when the recommended person signs up.

Or is there a different method that I can use instead?

A: 

One approach is to wrap those fields as a virtual attribute, say:

class Example < ActiveRecord::Base

  validates_presence_of :referral

  def referral
    user_id || user_email
  end
end

or you can just throw a custom validate validation method. See custom validations on the Rails API

If both user_id and user_email come from another model, perhaps it's better to add the association instead

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
Chubas
Thanks heaps! Exactly what I needed!
Jty.tan
A: 
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? }
zed_0xff