Nithin Viswanathan
Nithin Viswanathan

Reputation: 3283

If Statement in ruby on rails

I have a task to list students' details. I want to perform searching based on name and city. If cityId==0 and name='', then I want to list all my student details. How can I do this? I did this in a wrong way. The controller is:

    if(Student.where(params[:cityId])==0)
    studentcount = Student.count()
    @students = Student.limit(params[:jtPageSize]).offset(params[:jtStartIndex]).order(params[:jtSorting])
    @jtable = {'Result' => 'OK','Records' => @students.map(&:attributes), :TotalRecordCount => studentcount}
    else
    studentcount = Student.where("name LIKE ? AND city = ?", "%#{params[:name]}%", params[:cityId]).count()
    @students = Student.where("name LIKE ? AND city = ?", "%#{params[:name]}%", params[:cityId]).limit(params[:jtPageSize]).offset(params[:jtStartIndex]).order(params[:jtSorting])
    @jtable = {'Result' => 'OK','Records' => @students.map(&:attributes), :TotalRecordCount => studentcount}

Upvotes: 0

Views: 110

Answers (2)

krichard
krichard

Reputation: 3694

Your condition should look like this:

 if( Student.where(:cityId => params[:cityId]).count == 0 )

The if-statement you have tests a ActiveRecord::Relation and an Integer for equality which will never be true

Upvotes: 1

tokland
tokland

Reputation: 67850

if User.where(city_id: params[:cityId]).empty?

Upvotes: 0

Related Questions