我當前的代碼:Rails:使用關聯時,不會在模型上調用method_missing
class Product < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
def method_missing name
true
end
end
Category.new.ex_undefined_method #=> true
Product.last.category.ex_undefined_method #=> NoMethodError: undefined method `ex_undefined_method' for #<ActiveRecord::Associations::BelongsToAssociation:0xc4cd52c>
這是因爲rails中的這個代碼只傳遞了模型中存在的方法。
private
def method_missing(method, *args)
if load_target
if @target.respond_to?(method)
if block_given?
@target.send(method, *args) { |*block_args| yield(*block_args) }
else
@target.send(method, *args)
end
else
super
end
end
end
這就是我想要的:
Product.last.category.ex_undefined_method #=> true
我怎樣才能做到這一點?
您的'Product'' belongs_to'行有錯字。這是在原始代碼中,還是隻是在這裏發佈的代碼? – Chowlett 2011-06-01 08:11:14
只是在這裏發佈的代碼。 – 2011-06-01 08:18:00
這是非常相似的:http://stackoverflow.com/questions/3386567/method-missing-override-is-not-working。我可能可以重寫BelongsToAssociation類的method_missing,但這似乎有點過於普遍。不是嗎? – 2011-06-01 08:19:34