[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
相关推荐
qq_372906932 分钟前
如何通过点击事件动态展开和收起 HTML 元素
jvm·数据库·python
qq_3721542315 分钟前
Golang Gin怎么做JWT登录认证_Golang Gin JWT教程【实用】
jvm·数据库·python
2401_8716965216 分钟前
C#怎么实现文件上传下载 C#如何用WebAPI实现大文件断点续传功能【网络】
jvm·数据库·python
m0_3776182318 分钟前
如何在 pytest 中通过组合多个 fixture 实现参数化测试
jvm·数据库·python
Full Stack Developme20 分钟前
Hutool StrUtil 教程
开发语言·网络·python
代码羊羊21 分钟前
Rust方法速览:从self到impl
开发语言·后端·rust
小糖学代码21 分钟前
LLM系列:2.pytorch入门:2.PyTorch张量运算
pytorch·python·aigc·numpy
子兮曰21 分钟前
独立开发者主流技术栈(2026最新)
前端·后端·全栈
给自己做减法22 分钟前
RAG调参实践一
python·ai编程·rag
djjdjdjdjjdj25 分钟前
Golang如何做本地缓存加速_Golang本地缓存教程【核心】
jvm·数据库·python