How to sort sql queries in the RUBY on Rails model?

4

I have the following method an ROR application.

query_student = "SELECT name, registration, room FROM students WHERE registration = "+
  params[:registration]+" AND password = "+params[:password]

  @student = ActiveRecord::Base.connection.execute(query_student)
  render :json => @student

It seems to me that in OOP it would not be legal to keep the query in CONTROLLER.

Does anyone know how I could throw this query to model and just instantiate and tals?

    
asked by anonymous 19.08.2016 / 19:56

3 answers

3

If you have the Students model, you do not need to mount sql

Students.where("registration = ?", params[:registration]).where("password = ?",params[:password]).order(:name)

If you do not have the Students template it is better to create

class Student < ActiveRecord::Base
    self.table_name="students"
    self.establish_connection :your_connection
end
    
21.08.2016 / 18:43
3

A simple way is to use the direct order method in the controler.

Ex:

@users = User.order('name DESC').all
  

In the above example we pass a query to the order method to list all users by name in the non-descending order.

You can also pass symbol, it is more elegant, but far from ideal. This is a model responsibility.

@users = User.order('name: :desc').all

Here you have everything you need! = D Active Record Query Interface

    
27.08.2016 / 02:08
2

Thanks for all the help, I managed to play the responsibility of sql for Model ...

I created a method in the model

def sqlValidatedLogin(registration,password)
        query_student = "SELECT id, name, registration, room FROM students WHERE registration = "+
        registration+" AND password = "+password
        ActiveRecord::Base.connection.execute(query_student)
        end

and in the controller, I instantiated the object.

def index
  student = Student.new
  return_dados = student.sqlValidatedLogin(params[:registration].to_s,params[:password].to_s)
  render :json => return_dados
  end

all resolved..vlw

    
30.08.2016 / 15:14