[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
相关推荐
AI技术增长2 分钟前
Pytorch图像去噪实战(二):用UNet解决DnCNN细节丢失问题(结构解析+完整代码+踩坑总结)
人工智能·pytorch·python
直奔標竿9 分钟前
Java开发者AI转型第二十二课!Spring AI 个人知识库实战(一)——架构搭建与核心契约落地
java·人工智能·后端·spring·架构
清汤饺子16 分钟前
【译】我的 AI 进阶之路:从怀疑到深度整合
前端·javascript·后端
dFObBIMmai22 分钟前
CSS如何检测页面浮动元素位置_使用审查工具与clear
jvm·数据库·python
qq_4609784026 分钟前
实现 Svelte 中基于数组索引的 details 元素单开单关交互
jvm·数据库·python
AI科技星37 分钟前
ELN 升级:π 级数自动生成器全域数理架构
大数据·人工智能·python·算法·金融
无厚1 小时前
Spring Boot中LLM流式交互的核心原理
后端·设计
用户9352013986791 小时前
淘宝开放平台 item_cat_get 接口详解:获取淘宝商品类目
python
dfdfadffa1 小时前
SQL窗口函数如何优化嵌套子查询_提升执行效率
jvm·数据库·python