在另一个范围内重用多个范围以在rails中创建搜索多个字段

时间:2016-08-23 02:45:16

标签: mysql ruby-on-rails ruby activerecord scope

我正在使用表单参数创建搜索范围,但我不知道如何将范围与条件组合或调用当前范围。 这是我的源代码

class Issue < ApplicationRecord

  default_scope { order(created_at: :desc) }

  scope :state, ->(flag = :open){
    where state: flag
  }

  scope :sort_by, ->(field = :github_id, sort_type = :asc){
    reorder({field.to_sym => (sort_type && sort_type.to_sym) || :asc })
  }

  scope :milestone, ->(milestone){
    where milestone: milestone
  }

  scope :assignee, ->(assignee){
    where assignee: assignee
  }

  scope :author, ->(author){
    where author: author
  }

  scope :search, ->(param={}){
    # assign result = default scope here and chain it using below scope
    sort_by(param[:sort_by],param[:sort_type]) if param[:sort_by].present?
    author(param[:author]) if param[:author].present?
    assignee(param[:assignee]) if param[:assignee].present?
    milestone(param[:milestone]) if param[:milestone].present?
  }

end

2 个答案:

答案 0 :(得分:2)

使用加号(未经测试):

scope :search, ->(param={}) {
  all
  + relation.sort_by(param[:sort_by],param[:sort_type]) if param[:sort_by].present?
  + relation.author(param[:author]) if param[:author].present?
  + relation.assignee(param[:assignee]) if param[:assignee].present?
  + relation.milestone(param[:milestone]) if param[:milestone].present?
}

另一个例子是:

User.where(thing: true) + User.where(thing: false)

因为它们都返回ActiveRecord::Relation个对象集合。

答案 1 :(得分:1)

您可以使用本地变量:

scope :search, ->(param={}) {
  relation = all
  relation = relation.sort_by(param[:sort_by],param[:sort_type]) if param[:sort_by].present?
  relation = relation.author(param[:author]) if param[:author].present?
  relation = relation.assignee(param[:assignee]) if param[:assignee].present?
  relation = relation.milestone(param[:milestone]) if param[:milestone].present?
  relation
}