开发者

Undefined Method 'Match' when using a :belongs_to association

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 ge开发者_开发百科t "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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜