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

标签 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

最佳答案

使用加号(未经测试):

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 对象集合。

关于mysql - 在另一个范围内重用多个范围以在 Rails 中创建搜索多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39091525/

相关文章:

php - MySQL 错误 1064

php - 从 PHP 准备语句返回一个 bool 值

mysql - 在 Mac 上为 Ruby on Rails 设置本地 Web 服务器

sql - 查找两个表之间重叠的最有效方法

ruby-on-rails - Ruby on Rails : Is there a method to retrieve an array of data from the database without Rails needing to instantiate anything?

ruby-on-rails - Stylesheet_link_tag :all versus :media =>all

mysql - 在关系数据库和非关系数据库之间同步分页

命令行下的Mysql(不能用所有的键盘按键)

ruby-on-rails - rails : How to filter and sort products?

ruby-on-rails - Rails - 多态收藏夹(用户可以收藏不同的模型)