[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
相关推荐
I疯子7 小时前
2026-04-13 打卡第 6 天
开发语言·python
HaiXCoder7 小时前
python从入门到精通-第6章: 元编程 — Python的"超能力"
python
素玥8 小时前
实训7 json文件数据用python导入数据库
数据库·python·json
千枫s8 小时前
做一个电脑版爬虫程序
爬虫·python
大邳草民8 小时前
Python 对象模型与属性访问机制
开发语言·笔记·python
weixin_402486348 小时前
小分子 pdb准化为sdf
python
橘子编程8 小时前
密码学完全指南:从基础到实战
java·python·密码学
蓝色的杯子8 小时前
Python面试30分钟突击掌握-LeetCode2-Strings
python
昵称为空C8 小时前
在复杂SpringBoot项目中基于hutool实现临时添加多数据源案例
spring boot·后端
ZC跨境爬虫8 小时前
海南大学交友平台开发实战 day9(头像上传存入 SQLite+BLOB 存储 + 前后端联调避坑全记录)
前端·数据库·python·sqlite