我正在复制我的includes
,where
,order
和paginate
方法,因为我不知道是否存在Arel链的阻止或更好的方法让这个干。是否有一些东西可以很容易地测试params中的specialty_id或facility_id而不使用带有三元运算符的长where
字符串?
class << self
def list(options = {})
facility_id = options[:facility_id] || nil
keywords = options[:keywords] || nil
page = options[:page] || nil
specialty_id = options[:specialty_id] || nil
jobs = self.arel_table
unless keywords.nil?
keywords = keywords.downcase.tr_s('^a-z0-9 ', '').tr_s(' ', '\%')
end
if !specialty_id.blank?
approved.
includes(:facility, :specialties, :videos).
where(jobs[:name].matches("%#{keywords}%")).
where(specialties: {id: specialty_id}).
order(jobs[:name]).
paginate(page: page, per_page: 20)
elsif !facility_id.blank?
approved.
includes(:facility, :specialties, :videos).
where(jobs[:name].matches("%#{keywords}%")).
where(facilities: {id: facility_id}).
order(jobs[:name]).
paginate(page: page, per_page: 20)
else
approved.
includes(:facility, :specialties, :videos).
where(jobs[:name].matches("%#{keywords}%")).
order(jobs[:name]).
paginate(page: page, per_page: 20)
end
end
end
答案 0 :(得分:2)
query = approved
query = query.includes(:facility, :specialties, :videos)
query = query.where(jobs[:name].matches("%#{keywords}%")) if jobs[:name].present?
query = query. ...
query = query.paginate(page: page, per_page: 20)
query.to_a
答案 1 :(得分:1)
您应该能够将这些链接在一起,以便在执行之前进行构建。
这样的事情应该是可能的:
scoped.tap do |query|
query.
approved.
includes(:facility, :specialties, :videos).
where(jobs[:name].matches("%#{keywords}%"))
query.where(specialties: { id: specialty_id }) if specialty_id.present?
query.where(facilities: { id: facility_id }) if facility_id.present?
query.order(jobs[:name]).paginate(page: page, per_page: 20)
end
有关scoped
的更多信息,请参阅here。