[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
相关推荐
q***82912 分钟前
Spring Boot 热部署
java·spring boot·后端
Victor3562 分钟前
Redis(131)Redis的整数集合(Intset)是如何实现的?
后端
yuuki2332331 小时前
【数据结构】栈
c语言·数据结构·后端
cheniie1 小时前
python xmlrpc踩坑记录
python·踩坑·xmlrpc
咖啡の猫3 小时前
搭建Python开发环境
开发语言·python
程序猿小蒜4 小时前
基于springboot的共享汽车管理系统开发与设计
java·开发语言·spring boot·后端·spring·汽车
听风吟丶5 小时前
Java 8 Stream API 高级实战:从数据处理到性能优化的深度解析
开发语言·python
q***46525 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
hygge9995 小时前
Spring Boot + MyBatis 整合与 MyBatis 原理全解析
java·开发语言·经验分享·spring boot·后端·mybatis
q***13615 小时前
十七:Spring Boot依赖 (2)-- spring-boot-starter-web 依赖详解
前端·spring boot·后端