Hi

I have three models:

class Product < ActiveRecord::Base
  has_many :coupons
  has_many :orders
end

class Coupon < ActiveRecord::Base
  belongs_to :product
end

class Order < ActiveRecord::Base
  belongs_to :product
end

When creating an order, a coupon can be supplied to make use of a
discount. I want to validate that the coupon given is indeed belonging
to the product the user is trying to buy (and not some other random
product).

If I where just to validate that the coupon existed at all, I could
write the following inside the Order model:
validates_inclusion_of :coupon, :in => Coupon.all.map(&:code)

But how do I validate that it is belonging to the correct product?
I've tried:

validates_inclusion_of :coupon, :in => product.coupons.map(&:code)

But then I get an error: "undefined local variable or method product"
Then I've tried both:

validates_inclusion_of :coupon, :in => lambda { product.coupons.map
(&:code) }
and
validates_inclusion_of :coupon, lambda { { :in => product.coupons.map
(&:code) } }

But then I get the error: "An object with the method include? is
required must be supplied as the :in option of the configuration hash"

How can I do this?

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to