Making a RAW SQL connection and rendering JSON for custom auto complete field
Jump to navigation
Jump to search
In any model class:
def self.labels_for_autocomplete(auto_c_req)
connection.select_all("SELECT label FROM companies WHERE LOWER(label) LIKE '#{auto_c_req.downcase}%' ORDER BY label ASC LIMIT 10 ")
end
connection outpass ActiveRecords and does not cast results as Ruby objects.
in the controller:
def suggest_entreprises
if request.xhr? if request.post? auto_c_req=params[:auto_c_req] results=Company.labels_for_autocomplete auto_c_req render :json => results.to_json end end render :text => "Error" end
This example renders as JSON, and accepts only POST XHR requests.