Forum: Ruby on Rails validates_inclusion_of using model association?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ed0ce2998995c2b649c31ca06a72dae4?d=identicon&s=25 Thomas Watson (wa7son)
on 2009-02-18 15:51
(Received via mailing list)
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?
D69d23d8e811e8ab2a8593380d6ede63?d=identicon&s=25 Jeff Emminger (jemminger)
on 2009-02-18 16:35
(Received via mailing list)
try

validates_inclusion_of :coupon, :in => lambda { |prod| prod.coupons.map
(&:code) }
Ed0ce2998995c2b649c31ca06a72dae4?d=identicon&s=25 Thomas Watson (wa7son)
on 2009-02-18 16:51
(Received via mailing list)
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"
This topic is locked and can not be replied to.