如何在Ruby Sunspot中定义动态范围?

时间:2011-09-26 08:41:13

标签: ruby-on-rails ruby sunspot

我想通过“全部”过滤器或“任何”过滤器搜索曲目。所以这就是我得到的:

tracks_controller.rb

def search
  if params[:scope] == "any_of"
    Track.search do
      any_of do
        with(:name, "Thriller")
        with(:artist, "Michael Jackson")
      end

      with(:user_id, current_user.id)
    end
  elsif params[:scope] == "all_of"
    Track.search do
      all_of do
        with(:name, "Thriller")
        with(:artist, "Michael Jackson")
      end

      with(:user_id, current_user.id)
    end
end

它按预期工作。但是如何重构代码使其变干?

1 个答案:

答案 0 :(得分:2)

主席先生:

def search
  Track.search do

    mode = (params[:scope] == 'any_of' ? method(:any_of) : method(:all_of)) # don't use method(params[:scope]) for obvious security reason)

    mode.call do
      with(:name, "Thriller")
      with(:artist, "Michael Jackson")
    end

    with(:user_id, current_user.id)
  end
end