Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Like operator in ruby on rails

I had got a task to select search the students those name start with param value and city in the selected value.How can i set in ruby on rails? i did like this but this is not working controller

 def list

    studentcount=Student.count()
    puts studentcount
    @studentname = Student.where("name name1 AND city = :cityId1",
    {:name1 => params[:name], :cityId1 => params[:cityId]})

    puts 'studentname'
    puts @studentname.inspect
    @students = Student.limit(params[:jtPageSize]).offset(params[:jtStartIndex]).order(params[:jtSorting])

    @jtable = {'Result' => 'OK','Records' => @students.map(&:attributes), :TotalRecordCount => studentcount}

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @jtable}
    end
  end
like image 452
Nithin Viswanathan Avatar asked Dec 07 '12 07:12

Nithin Viswanathan


Video Answer


2 Answers

Try

@studentname = Student.where("name LIKE ? AND city = ?", "#{params[:name]}%", params[:cityId])
like image 78
Sandip Karanjekar Avatar answered Oct 27 '22 19:10

Sandip Karanjekar


Try:

@studentname = Student.where("name LIKE :name1 AND city = :cityId1",
  {:name1 => "#{params[:name]}%", :cityId1 => params[:cityId]})

This is a rather dirty solution, but pure ARel cannot handle this case the way you desire. You might want to try the Sqeel gem.

like image 13
Christoph Petschnig Avatar answered Oct 27 '22 19:10

Christoph Petschnig