[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
相关推荐
cxr8282 小时前
大语言模型上下文缓存命中率测试全场景清单
人工智能·python·算法·缓存·语言模型·自然语言处理·llm
用户6757049885022 小时前
别再乱用了!var arr []int 和 arr := []int{} 给整懵了?不就声明个空数组,项目居然崩了?
后端·go
某林2122 小时前
大模型边缘部署到底层硬件闭环
python·架构·机器人·硬件架构·ros2
马达拉3 小时前
为什么Bun查询数据库接口响应比Rust还快
后端
LadenKiller3 小时前
最新量化软件选择,先按能力判断表达生成和执行
人工智能·python
geovindu3 小时前
go: Enumeration Algorithm
开发语言·后端·算法·golang·枚举算法
iuu_star3 小时前
Python大模型智能学习平台——设计与实现(AI教学系统)
大数据·人工智能·python·学习
雪隐3 小时前
个人电脑玩AI-10让5060 Ti给你打工——ComfyUI,我差点被它劝退三次
人工智能·后端
天才测试猿3 小时前
如何封装自动化测试框架?
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
工具派4 小时前
写代码时,我把这个本地 AI Commit Message 生成器接进了工作流
前端·后端