2
votes

I have a :belongs_to association defined on model Brand as follows:

belongs_to  :loyalty_coupon, :class_name => Coupon, :foreign_key => :loyalty_coupon_id

(There is also a :has_many relationship from Brand to Coupon, but the :belongs_to relationship is intended to single out one particular coupon for special attention. Relationship names and linking fields are different between the two associations, so there should be no conflict; I only mention this as it could prove relevant. The relationship is expressed as has_many :coupons and belongs_to :brand.)

When I display Brand.first.loyalty_coupon, I get "nil" (that's okay because I haven't assigned one yet). When I attempt to assign a loyalty_coupon with the command Brand.first.loyalty_coupon = Coupon.first, I get the error message:

undefined method `match' for #<Class:0x104036d30>

with a partial traceback as follows:

activerecord (3.0.1) lib/active_record/base.rb:1016:in `method_missing'
activerecord (3.0.1) lib/active_record/base.rb:1180:in `compute_type'
activerecord (3.0.1) lib/active_record/reflection.rb:162:in `send'
activerecord (3.0.1) lib/active_record/reflection.rb:162:in `klass'
activerecord (3.0.1) lib/active_record/reflection.rb:173:in `build_association'

Same error message if I do Brand.first.build_loyalty_coupon (not surprising since it's doing the same thing). I had no :has_one in the Coupon model, but I also tried that with :class_name and :foreign_key specified, and got the same error and traceback when I tried Coupon.first.brand_loyalty. I imagine that I'm missing something stupid, but I can't see what it is.

1
You need foreign_key and class names on both sides of the relationship for the has_one :loyalty_coupon etc... Give it a tryjamesc
@jamesw: Correct. This unfortunately will not fix the issue though.Ryan Bigg

1 Answers

10
votes

Your :class_name option should be a String, not a Class object. This is so that ActiveRecord does not attempt to load "class B" which may reference "class A" which would reference "class B" and so on and so forth.

belongs_to  :loyalty_coupon, :class_name => "Coupon"

String objects have the match method while Class objects do not.

You don't need to include the :foreign_key option, as it is inferred from the association's name.