有没有办法使用一个命令来检索所有行并过滤它们?
所以,现在我有条件逻辑
if rating_filter.nil?
@movies = Movie.all
else
@movies = Movie.find(:all, :conditions => {:rating => rating_filter})
end
即如果未设置字段过滤器,我不想按此字段过滤,但如果我将 nil 传递给第二个命令,我将得到:
SELECT * FROM movies WHERE rating is NULL, though I need
SELECT * FROM movies
如果我有多个参数,就会出现问题。如果两者都设置,那么没问题:
@movies = Movie.find(:all, :conditions => {:rating => rating_filter, :date => date_filter})
但是如果没有设置一个过滤器,我需要分支我的逻辑以获取单独的命令:
if ..
@movies = Movie.find(:all, :conditions => {:rating => rating_filter)
else
@movies = Movie.find(:all, :conditions => {:date => date_filter})
else
@movies = Movie.all
end
有没有减少代码行的技巧,理想情况下是一个?=)