0

我在搜索表单中使用了以下代码。我希望能够将作用域方法与 by_title 链接起来,但我看不到如何。我想将 by_title 作为一种方法,而不仅仅是这样做:

# Arel helpers
  class << self
    def by_city(city)
      where(['city_id = ?', city])
    end
    def by_title(title)
      where('title LIKE ?', "%#{title}%")
    end
  end


  def self.search(search_params)
    experiences = scoped
    experiences.self.by_title(search_params[:title]) if search_params[:title]
  end
4

2 回答 2

2

你为什么不这样玩范围:

scope :by_title, lambda { |title| where('title LIKE ?', "%#{title}%") }
scope :by_city,  lambda { |city|  where('city_id = ?', city) }
于 2013-01-04T22:42:57.550 回答
1

通过删除self它应该可以工作,我认为:

experiences = scoped
experiences.by_title(search_params[:title]) if search_params[:title]

scoped方法返回一个匿名范围,可以与其他范围/类方法链接。

于 2013-01-05T01:35:18.100 回答