2012-04-04 31 views
0

我有三种模型。 1-产品 2-自行车 3-汽车为什么模型object.save触发missing_method(rails 2.2)

这些模型具有多态关联。产品型号包括自行车和汽车的共同的东西:如价格,颜色等

现在我想直接通过汽车或自行车的像bike_obj.price对象访问产品的方法

def method_missing(meth, *args, &blk) 
    product.send(meth, *args, &blk) 
rescue NoMethodError 
    super 
end 

现在我能够实现这个

>> Car.last.price 
=> 1000 

但问题是汽车模型已停止工作的保存方法。当我做Car.last.save时,我不知道为什么它会在method_missing中进行。它提出了这个例外

NoMethodError: undefined method `<=>' for #<Car:0x7fcdd39ef2c0> 
+0

你知道Rails的#delegate方法? IT可能对您有用:http://api.rubyonrails.org/classes/Module.html#method-i-delegate – joelparkerhenderson 2012-04-04 08:31:16

+0

是的一种方法是将方法委托给产品模型。但这样我不得不委托一大堆方法。然后我想通过method_missing来实现它。不幸的是,这不适合我 – 2012-04-04 09:05:02

回答

1

您应该重写respond_to?每当你覆盖method_missing

def respond_to?(method, include_private = false) 
    super || product.respond_to?(method, include_private) 
    end