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
我该怎么做?     
已邀请:
        请注意,“ 3”对象仅发送目标声明为“ 4”的方法。因此,解决方法是同时更新
respond_to?
class Category < ActiveRecord::Base
  def method_missing(name, *args, &block)
    if name =~ /^handleable/
      \"Handled\"
    else
      super
    end
  end

  def respond_to?(name)
    if name =~ /^handleable/
      true
    else
      super
    end
  end
end
实际上,如果您重新定义
method_missing
,则应该始终更新
respond_to?
-您已经更改了班级的界面,因此需要确保每个人都知道它。看这里。     
        乔莱特的反应确实是去恕我直言的方法。 但是,如果您使用的是Rails 3 *,请确保包括在reacts_to中引入的第二个参数?定义:
def respond_to?(name,include_private = false)
  if name =~ /^handleable/
    true
  else
    super 
  end
end
    
        更换
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
通过
if block_given?
  @target.send(method, *args)  { |*block_args| yield(*block_args) }
else
  @target.send(method, *args)
end
作为AssociationProxy的猴子补丁     

要回复问题请先登录注册