【问题标题】:Trying to find a good way to chain scopes dynamically试图找到一种动态链接作用域的好方法
【发布时间】:2018-01-07 07:01:52
【问题描述】:

我发现这篇关于清理链式作用域的文章在我正在从事的项目中非常有用。但是,我的一些范围有参数。我想不出一种方法来使这个工作与争论。我尝试了字符串插值,我怀疑它不起作用,当然,没有。

https://www.sitepoint.com/dynamically-chain-scopes-to-clean-up-large-sql-queries/

def self.send_chain(methods)
  methods.inject(self, :send)
end

$ methods = ["with_author", "pending_review", "draft", "flagged", "published", "with_website", "with_meta_title", "with_meta_description"]
$ Article.send_chain(methods)

【问题讨论】:

    标签: ruby-on-rails-3 scopes


    【解决方案1】:
    def send_chain(methods)
      methods.inject(self) { |result, method| result.send(*method) }
    end
    

    方法应该是一个数组,如果一个方法需要一个或多个参数,那应该是一个子数组

    [:foo, [:bar, "argument"], :baz]
    

    【讨论】:

      猜你喜欢
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2012-04-17
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多