validates_inclusion_of using model association?

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?

try

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

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