0

有没有一种obj.update(attr1: "something")方法可以调用method_missing而不是引发错误ActiveModel::UnknownAttributeError (unknown attribute 'attr1' for Obj.)

我正在考虑简单地拯救它,然后模仿/调用method_missing,但这种方式感觉太笨重了。

4

3 回答 3

3

源代码(Rails 4.2)看来,ActiveRecord::UnknownAttributeError当模型实例不respond_to?使用给定的属性设置器时会引发。所以你要做的就是在模型中为你的所有动态属性定义一个method_missing以及。respond_to_missing?这实际上是您在使用时始终应该做method_missing的事情:

class Model < ActiveRecord::Base

  DYNAMIC_ATTRIBUTES = [:attr1, :attr2]

  def method_missing(method_name, *arguments, &block)
    if DYNAMIC_ATTRIBUTES.map { |attr| "#{attr}=" }.include?(method_name.to_s)
      puts "custom code for #{method_name} #{arguments.first.inspect}"
    else
      super
    end
  end

  def respond_to_missing?(method_name, include_private = false)
    DYNAMIC_ATTRIBUTES.map { |attr| "#{attr}=" }.include?(method_name.to_s) || super
  end

end

在 Rails 控制台中测试:

Model.first.update(attr1: 'aa', attr2: 'bb')
# => custom code for attr1= "aa"
# => custom code for attr2= "bb"

Model.first.update(attr1: 'aa', attr2: 'bb', attr3: 'cc')
# => ActiveRecord::UnknownAttributeError: unknown attribute 'attr3' for Model.
于 2016-05-23T09:25:17.573 回答
0

像这样的东西?

  rescue_from ActiveModel::UnknownAttributeError do |exception|
    raise NoMethodError
    # or however you want to hanle
  end
于 2016-05-23T07:33:25.810 回答
0

你可以试试这个:

begin
  obj.update(attr1: "something")
rescue Exception => ex
  if  ex.class == ActiveRecord::UnknownAttributeError
    method_missing
  else
    raise ex
  end
end
于 2016-05-23T07:43:28.967 回答