【问题标题】:Rails Model scope chaining based on dynamic scope name list基于动态范围名称列表的 Rails 模型范围链接
【发布时间】:2017-10-12 04:02:22
【问题描述】:

假设我有一些模型

class MyModel < ApplicationRecord
  scope :opened, -> { where(status: 'open') }
  scope :closed, -> { where(status: 'closed') }
  scope :colored, -> { where.not(color: nil) }
  # etc
end

我可以像这样调用作用域链

MyModel.opened.colored
MyModel.send('opened').send('colored')

但是如何根据动态范围令牌列表进行范围链接?我是说

scopes = ['opened', 'colored', ...]

这个列表可能很长,我需要一些通用的解决方案来尽可能简单,比如MyModel.send_list(scopes)

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord


    【解决方案1】:

    更多作为范围的结果,您可以添加喜欢,

    scope :send_list, -> (*scopes) { scopes.inject(self) { |out, scope| out.send(scope) } }
    

    这样发送YourModel.send_list(*scopes)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2012-12-13
      • 1970-01-01
      相关资源
      最近更新 更多