[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
相关推荐
摇滚侠13 分钟前
《SpringBoot 3:入门与应用实战》第 2 章 IOC 思想与实现 阅读笔记 1
spring boot·笔记·后端
金銀銅鐵25 分钟前
[Python] 借助 turtle 逐字展示唐诗《金缕衣》
python
山荷枝30 分钟前
03-框架--Spring
java·后端·spring
ChaHae-In1 小时前
SpringBoot统一功能处理
java·spring boot·后端
Python大数据分析@2 小时前
使用大模型MCP采集数据,爬虫已经无门槛
python·网络爬虫
quantdash_cc3 小时前
告别自建 Requests/BS4 网页爬虫:基于 QuantDash 搭建零维保的高性能量化行情流水线
开发语言·爬虫·python·pandas·量化·quantdash
65岁退休Coder3 小时前
LangChain v1.3.4 笔记 - 07 补充:链式调用 LCEL
后端·python·langchain
卷无止境3 小时前
FastAPI 部署在 Nginx 后面到底该怎么配
后端·python
码流怪侠3 小时前
用 WiFi 信号数人头:howmanypeoplearearound 项目深度解析
后端·开源·github