# Validates\_inclusion\_of using model association?

**URL:** <https://www.ruby-forum.com/t/validates-inclusion-of-using-model-association/160662>\
**Category:** Rails\
**Created:** [February 18, 2009, 3:51pm UTC](https://www.ruby-forum.com/t/validates-inclusion-of-using-model-association/160662 "2009-02-18T15:51:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![wet](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/848f3c/32.png) [@wet](https://www.ruby-forum.com/u/wet)\
**Post date:** [February 18, 2009, 3:51pm UTC](https://www.ruby-forum.com/t/validates-inclusion-of-using-model-association/160662/1 "2009-02-18T15:51:16Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![wet](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/848f3c/32.png) [@wet](https://www.ruby-forum.com/u/wet)\
**Post date:** [February 18, 2009, 4:35pm UTC](https://www.ruby-forum.com/t/validates-inclusion-of-using-model-association/160662/2 "2009-02-18T16:35:12Z")

</div>

try

validates\_inclusion\_of :coupon, :in =\> lambda { |prod| prod.coupons.map  
(&:code) }

---

<div class="post-metadata">

**Author:** ![wet](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/848f3c/32.png) [@wet](https://www.ruby-forum.com/u/wet)\
**Post date:** [February 18, 2009, 4:51pm UTC](https://www.ruby-forum.com/t/validates-inclusion-of-using-model-association/160662/3 "2009-02-18T16:51:04Z")

</div>

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”
