KhiemNS KhiemNS - 1 year ago 45
MySQL Question

reuse multiple scopes in another scope to create search multiple fields in rails

I'm creating scope for searching using form parameter but I don't know how to combine scope with conditions or call current scope.
Here is my source code

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?


Answer Source

You can use a local variable:

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