链接Active Record方法错误

时间:2013-01-04 22:18:34

标签: ruby-on-rails activerecord

我在搜索表单中使用了以下代码。我希望能够使用by_title链接scoped方法,但我没有看到如何。我希望将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

2 个答案:

答案 0 :(得分:2)

为什么不用这种方式玩范围:

scope :by_title, lambda { |title| where('title LIKE ?', "%#{title}%") }
scope :by_city,  lambda { |city|  where('city_id = ?', city) }

答案 1 :(得分:1)

只需删除self即可,我认为:

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

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