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

Asked

Viewed 670 times

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

However it seems to me that in the POO it would not be nice to keep the query in the CONTROLLER.

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

3 answers

3


If you have the Students model you don’t need to mount sql

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

If you don’t have the Students template you better create

class Student < ActiveRecord::Base
    self.table_name="students"
    self.establish_connection :your_connection
end
  • I understood, otmo, however this was an example I have other queries that had to be customized with pure sql even, and I would like to put them in the model and only instantiates them... Queries that use 3 JOINS and SUM

3

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

Ex:

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

In the above example we passed a query to the order method to list all users by name in the unbelieving order.

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

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

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

  • our thanks so much for the help, but really that’s the point, I would like to play this responsibility of consultations for the Model, as I could take from the controller and play for the Model ?

2

Thank you all for your help, I managed to play sql responsibility 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 installed 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 solved. vlw

  • Mark your answer as accepted to guide other users. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.