ruby-on-rails – Ruby on Rails:模型之间的共享方法
发布时间:2020-12-16 20:43:18 所属栏目:百科 来源:网络整理
导读:如果我的几个模型有一个隐私列,有没有办法我可以写一个所有模型共享的方法,我们称它为is_public? 所以,我想要做object_var.is_public? 解决方法 一种可能的方法是将共享方法放在这样的模块中(RAILS_ROOT / lib / shared_methods.rb) module SharedMethods
如果我的几个模型有一个隐私列,有没有办法我可以写一个所有模型共享的方法,我们称它为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中有一个new way这样做.您应该将这样的共享代码放在app / models / concern中而不是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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |