如果我的几个模型都有一个隐私列,那么是否有一种方法可以编写一个适用于所有模型的方法,我们称之为is_public?
因此,我希望能够执行object_var.is_public?
如果我的几个模型都有一个隐私列,那么是否有一种方法可以编写一个适用于所有模型的方法,我们称之为is_public?
因此,我希望能够执行object_var.is_public?
一种可能的方法是将共享方法放在一个类似于这样的模块
中(RAILS_ROOT/lib/shared_methods.rb
)
module SharedMethods
def is_public?
# your code
end
end
那么您需要在每个需要使用这些方法的模型中包含此模块(即app/models/your_model.rb
)。
class YourModel < ActiveRecord::Base
include SharedMethods
end
更新:
在Rails 4中,有一种新的方式来做这件事。你应该把共享的代码放在app/models/concerns
而不是 lib
中。
此外,你还可以像这样添加类方法并在包含时执行代码:
module SharedMethods
extend ActiveSupport::Concern
included do
scope :public, -> { where(…) }
end
def is_public?
# your code
end
module ClassMethods
def find_all_public
where #some condition
end
end
end
您还可以通过从包含共享方法的公共祖先继承模型来实现此操作。
class BaseModel < ActiveRecord::Base
def is_public?
# blah blah
end
end
class ChildModel < BaseModel
end
实际上,jigfox的方法通常更好,因此不要仅仅出于对OOP理论的热爱而感到必须使用继承 :)
Table 'socha-webapp.test_client_managers' doesn't exist
。 - xeruf