[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
相关推荐
Moment1 小时前
Vibe Coding 时代,到底该选什么样的工具来提升效率❓❓❓
前端·后端·github
Victor3561 小时前
MongoDB(27)什么是文本索引?
后端
可夫小子2 小时前
OpenClaw基础-3-telegram机器人配置与加入群聊
后端
IT_陈寒3 小时前
SpringBoot性能飙升200%?这5个隐藏配置你必须知道!
前端·人工智能·后端
aiopencode4 小时前
使用 Ipa Guard 命令行版本将 IPA 混淆接入自动化流程
后端·ios
掘金者阿豪4 小时前
Kavita+cpolar 打造随身数字书房,让资源不再混乱,通勤 、出差都能随心读。
后端
helloweilei4 小时前
python 抽象基类
python
心之语歌4 小时前
Spring Security api接口 认证放行
后端
用户8356290780514 小时前
Python 实现 PPT 转 HTML
后端·python
0xDevNull4 小时前
MySQL索引进阶用法
后端·mysql