I have two models Customer and Referal. Both have an email attribute. Referal belongs to Customer and Customer has_many Referals.
When I create/update a Referal I want to check that email on the Referal does not equal email on the Customer (parent) object.
Here’s my Referal object: (cut out irrelevant stuff)
class Referal < ActiveRecord::Base
belongs_to :user
belongs_to :customer
validates :name, :presence => true
validates :email, :presence => true
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
validate :email_cannot_equal_referers
def email_cannot_equal_referers
if email == customer.email
errors.add(:email, "can't be the same as referer's")
end
end
end
Here’s Customer:
class Customer < ActiveRecord::Base
has_many :referals
validates_presence_of :name, :email
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :allow_blank => true
end
When I try to save Referal I get “undefined method `email’ for nil:NilClass”, which refers to customer.email as it works when I put email==email.
At this point Referal is not written to the database yet, though customer_id seems to be set, as I can use it in the error message (with .to_s), but it doesn’t work either to use this to search for Customer object using Customer.find(customer_id). (Couldn’t find Customer without an ID)
For completeness here is the controller bit that calls the save method on Referal:
@refer=Referal.new
@refer.name=params[:Name2]
@refer.email=params[:Email2]
@refer.message=params[:Message]
@customer.referals << @refer
if @refer.save
CustomerMailer.refer(@refer).deliver
CustomerMailer.refer_thanks(@refer).deliver
else
render 'new_refer'
end
Would greatly appreciate pointers to make this work!
Thanks
If the customer already exists in the db the validation you have should work.
If you are trying to create the customer and the referrals at the same time I would use the accepts_nested_attributes_for method through the customer model. I think you might have to add a validation in the customer model that iterates through the referrals.
then in your controller