patternrubyrailsMinor
User search controller
Viewed 0 times
usersearchcontroller
Problem
I am using the ruby sunspot gem to create a search users function on my site.
It works fine and the users controller for the index page where there is a search form is this
on the index page, I do this
My question is this. I think setting @users to nil looks and feels wrong. I want the index page to show nothing but my search form if nothing is put in the field. There must be some easy Ruby way to express this. By the way I am fairly new to Ruby on Rails.
It works fine and the users controller for the index page where there is a search form is this
def index
if params[:search].nil?
@users = nil
else
@search = User.search do
fulltext params[:search]
end
@users = @search.results.paginate(page: params[:page], :per_page => 10)
end
endon the index page, I do this
My question is this. I think setting @users to nil looks and feels wrong. I want the index page to show nothing but my search form if nothing is put in the field. There must be some easy Ruby way to express this. By the way I am fairly new to Ruby on Rails.
Solution
How about using the ternary operator and assigning the result to the variable?
def index
@users = params[:search].nil? ? nil : User
.search { fulltext params[:search] }.results
.paginate(page: params[:page], per_page: 10)
endCode Snippets
def index
@users = params[:search].nil? ? nil : User
.search { fulltext params[:search] }.results
.paginate(page: params[:page], per_page: 10)
endContext
StackExchange Code Review Q#86585, answer score: 3
Revisions (0)
No revisions yet.