如何在 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
它按预期工作。但如何重构代码使其变得 DRY 呢?
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, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是先生:
Here it is Sir: