How to define a dynamic scope in Ruby Sunspot?
I want to search the tracks either by "all of" the filters, or by "any of" the filters. So here is what I got:
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, 开发者_Python百科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
It works as expected. But how to refactor the code to make it DRY?
Here it is Sir:
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
精彩评论