我正在使用表单参数创建搜索范围,但我不知道如何将范围与条件相结合或调用当前范围。 这是我的源代码
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/