[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
相关推荐
楼田莉子6 小时前
Linux网络:数据链路层
linux·服务器·开发语言·网络·c++·后端
chushiyunen6 小时前
npy文件笔记
笔记·python
念恒123066 小时前
Python(列表入门)
python·学习
派星6 小时前
SpringBoot全局异常处理
后端
skilllite作者6 小时前
Warp 终端效能与交互体验全景展示
人工智能·后端·架构·rust
zjy277776 小时前
Go语言怎么用GitHub Actions_Go语言GitHub Actions教程【基础】
jvm·数据库·python
2301_782040456 小时前
如何实现SQL用户行为追踪_通过触发器记录操作明细
jvm·数据库·python
hrhcode6 小时前
【LangGraph】五.人机协作:审批和中断
python·ai·langchain·agent·langgraph
dFObBIMmai6 小时前
golang如何实现数据导入进度跟踪_golang数据导入进度跟踪实现教程
jvm·数据库·python
步辞6 小时前
golang如何实现即时通讯IM系统_golang即时通讯IM系统实现方案
jvm·数据库·python