Reputation: 1956
I have the following in my events
controller:
def index
@event = Event.search(params[:search]).events_by_category(params[:cat]).order(...).paginate(...)
end
And in my events
model, I have the following class method:
def self.events_by_category(cat)
if cat == 0
all
elsif cat && cat != 0
where('category = ?', cat)
else
scoped
end
end
And in my view I have a standard search box for the search and dropdown for the category selection. The category options_for_select
has an array that includes ["All Categories", 0]
in it.
My question is: Why does this return no results instead of all results when All Categories is selected in the dropdown. And, when I change the array to ["All Categories", "ALL"]
and the if statement to if cat == "ALL"
it returns Undefined method 'order'
?
I think it has something to do with stringing the search and events_by_category together in the controller, but searches and categories work just fine in conjunction when it's not All Categories being selected...
Any help would be GREATLY appreciated!
Upvotes: 0
Views: 222
Reputation: 27374
To answer your second question first: the problem is that your cat == "ALL"
condition returns Event.all
, which is a Ruby Array
, not an ActiveRecord::Relation
. order
is an activerecord method not an array method, that's why you're getting the error Undefined method 'order'
.
If you want to return all results for the category ALL
, then change all
to scoped
(which will return a scope with no conditions on it). That will be chainable, so that you can call it with order
and paginate
.
As to your first question, params[:cat]
is a string so you should be checking whether cat == "0"
not cat == 0
. I think that should solve the problem.
Your conditional, by the way, is a bit convoluted: you're testing if cat
is 0, then checking that it is not 0 in the else statement, but you already know that it is not 0. I'd suggest simplifying your method code to this:
def self.events_by_category(cat)
(cat && cat != "0") ? where('category = ?', cat) : scoped
end
This says: if the category is present and not "0"
(i.e. not the category "all results"), then return results for that category, if not return all results.
Upvotes: 2
Reputation: 1305
def self.events_by_category(cat)
if cat == "0"
all
elsif cat && cat != "0"
where('category = ?', cat)
else
scoped
end
end
The above will work.
Upvotes: 0