本文介绍了在ActiveRecord模型中使用def_method的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有如下所示的AR模型,我想动态生成一些实例方法,例如#fallbackable_header_script, #fallbackable_header_content...等,就像我已经编写的#fallbackable_background一样.最好的方法是什么?

So I have AR model like the following, and I want to dynamically generate a few instance methods like #fallbackable_header_script, #fallbackable_header_content... etc, just like the #fallbackable_background I've already written. What's the best way to do this?

class Course < ActiveRecord::Base
  FALLBACKABLE_ATTRIBUTES = :header_script, :header_content, :footer_content
  OTHER_FALLBACKABLE_ATTRIBUTES = :css_config

  def fallbackable_background
    read_attribute(:background) ? background : self.user.background
  end

end

我尝试了def_method,但是以下方法不起作用...

I tried def_method, but the following doesn't work...

  [:foo, :bar].each do |meth|
    fallbackable_meth = "fallbackable_#{meth}".to_sym
    def_method(fallbackable_meth) { read_attribute(meth) ? read_attribute(meth) : self.user.send(meth) }
  end
  #=>NoMethodError: undefined method `def_method' for #<Class:0x007fe4e709a208>

推荐答案

我认为它的define_method而不是def_method

I think its define_method and not def_method

[:foo, :bar].each do |meth|
    fallbackable_meth = "fallbackable_#{meth}".to_sym
    define_method(fallbackable_meth) { read_attribute(meth) ? read_attribute(meth) : self.user.send(meth) }
  end

您还可以使用def_each定义类似的方法

You can also use def_each to define similar methods

def_each :fallbackable_foo, :fallbackable_bar do |method_name|
 read_attribute(method_name) ? read_attribute(method_name) : self.user.send(method_name)
end

这篇关于在ActiveRecord模型中使用def_method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:24