- 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