SQL Like operator in ruby on rails

旧城冷巷雨未停 提交于 2019-12-05 21:24:20

问题


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

回答1:


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.




回答2:


Try

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



回答3:


there is a error in your methods, it should be like this

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


来源:https://stackoverflow.com/questions/13758844/sql-like-operator-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!