[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
相关推荐
小林coding20 分钟前
专为程序员打造的简历模版来啦!覆盖前端、后端、测开、大模型等专业简历
前端·后端
UrbanJazzerati31 分钟前
当网页翻页时,页码藏在哪里?——一次对分页机制的解密之旅
后端·面试
用户44904120955632 分钟前
一次生产环境下的Redis连接耗尽问题排查与解决全过程
后端
Tapir36 分钟前
被 Karpathy 下场推荐的 NanoClaw 是什么来头
前端·后端·github
ssshooter2 小时前
Tauri 项目实践:客户端与 Web 端的授权登录实现方案
前端·后端·rust
代码搬运媛2 小时前
Go 语言通道 (Channel) 深度用法讲解及实战
后端·go
程序员爱钓鱼2 小时前
Go生成唯一ID的标准方案:github.com/google/uuid使用详解
后端·google·go
Moment2 小时前
MinIO已死,MinIO万岁
前端·后端·github
无双_Joney2 小时前
心路散文 - 转职遇到AI浪潮,AIGC时刻人的价值是什么?
前端·后端·架构
树獭叔叔3 小时前
OpenClaw Tools 与 Skills 系统深度解析
后端·aigc·openai