1

我正在复制我includes的 、whereorderpaginate方法,因为我不知道是否有 Arel 链的块或更好的方法来使这个 DRY。where有没有什么东西可以在不使用三元运算符的长字符串的情况下轻松测试 params 中的 special_id 或 facility_id ?

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
4

2 回答 2

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
于 2012-04-24T21:23:47.423 回答
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请参见此处

于 2012-04-24T22:21:39.027 回答