[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
相关推荐
xufengzhu21 小时前
Python库PyMySQL的使用指南
开发语言·python·pip
骄马之死1 天前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
GoGeekBaird1 天前
Anthropic技能"(Skills)的经验分享
后端
王码码20351 天前
多台服务器怎么统一看状态?Beszel 轻量监控,搭起来不费事
运维·服务器·后端·安全·阿里云·接口·web
世辰辰辰1 天前
批量修改图片/文本名子
开发语言·python·批量修改文件名
郑洁文1 天前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
指令集梦境1 天前
Cursor + Spring Boot实战:从零写一个RESTful API
spring boot·后端·restful
myenjoy_11 天前
MQTT 与 Sparkplug B——从车间到云端的最后一公里
网络·python
码云之上1 天前
聊聊如何设计一个高效、稳定的 Node.js 接入层
前端·后端·node.js
颜酱1 天前
LangChain 输出解析器:把模型回复变成你要的数据
python·langchain