[ruby on rails] concerns的使用

  • concern是用来把公共的方法提取到一起,保持代码DRY,是用module来实现的

model中的concern

ruby 复制代码
module Visible
  extend ActiveSupport::Concern

  VALID_STATUSES = ['public', 'private', 'archived']  # 其他地方引用  Visible::VALID_STATUSES
 
  # 关联关系 blongs_to, has_many 、validates、 scope 都需要写到 included block中
  included do
    belongs_to :user

    validates :status, inclusion: { in: VALID_STATUSES }
    validate do
      errors[:name] << '请输入名称' if name.to_s.splict(',').size < 2
    end
    
    scope :public_count, -> { where(status: 'public').count }
    
    # 类方法一
    def self.public_count
      where(status: 'public').count
    end
    
    # 类方法二
    class << self
      def public_count
        where(status: 'public').count
      end
    end
     
	# 实例方法
    def public?
      status == 'public'
    end
  end
  
  # 类方法三,写到 included 外面
  class_methods do
    def public_count
      where(status: 'public').count
    end
  end

  # 实例方法
  def archived?
    status == 'archived'
  end
end
相关推荐
ZhengEnCi2 小时前
M3-markconv库找不到wkhtmltopdf问题
python
码事漫谈4 小时前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
2301_764441334 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
chushiyunen5 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA5 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
铁东博客5 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui5 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳5 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙5 小时前
Python_RAG知识库问答系统实战指南
开发语言·python