Is it possible to use If statements within a withCriteria block? I am trying to do the following:
allInfo = Scholarship.withCriteria {
//eq('gpa', gpa)
if (year != "All" || year != null) {
println "grades"
grades {
idEq year
}
}
if (county != "All" || county != null) {
println "county"
scholarshipCounties {
eq('county.id', county)
}
}
if (major != "All" || major != null) {
println "major"
majors {
idEq major
}
}
if (activity != "All" || activity != null) {
println "activity"
activities {
idEq activity
}
}
eq('specialTypeInd', special)
eq('activeInd', "A")
order("name", "asc")
}
year, county, major, and activity all are "All" when I am testing currently. I also already made sure they were Strings and not something else. Obviously It is printing out grades, county, etc when It shouldnt even be getting inside those if statements. So what is the problem? Thanks
Your Boolean logic looks faulty - a test like
if (year != "All" || year != null)
will always evaluate to true
for any value of year
- if year
is null then it is not "All" and vice versa. If you want the block to fire for any non-null year
value except "All" then it needs to be &&
instead of ||
.