HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

User search controller

Submitted by: @import:stackexchange-codereview··
0
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

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
end


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.

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)
end

Code Snippets

def index
  @users = params[:search].nil? ? nil : User
           .search { fulltext params[:search] }.results
           .paginate(page: params[:page], per_page: 10)
end

Context

StackExchange Code Review Q#86585, answer score: 3

Revisions (0)

No revisions yet.