2012-04-24 67 views
1

我複製了我的includes,whereorderpaginate方法,因爲我不知道是否存在Arel鏈的塊或更好的方式來製作此DRY。有沒有什麼東西可以很容易地在params中測試specialty_id或facility_id,而不需要使用帶有三元運算符的長字符串where如何有條件地從Rails 3.2 Arel方法鏈添加或刪除成員?

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 

回答

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 
+0

我以前試過,但它只使用'query.paginate'行。讓我檢查一下,看看我做錯了什麼。 – rxgx 2012-04-24 21:25:00

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

+0

太棒了。這是我正在尋找的塊。 – rxgx 2012-04-24 23:51:45

+0

不幸的是,tap不能使用'will_paginate'。 :(它必須跨越範圍 – rxgx 2012-04-25 01:03:57

+0

你使用的是Ruby 1.9+嗎? – Curtis 2012-04-25 21:09:29

相關問題