0

I need run a mysql query from the controller but I do not know how to connect to db.

this is my method:

def set_dcs
  sql="select employees.nombre, employees.apellido_paterno, employees.apellido_materno from employees, activities, field_tests
  where activities.field_test_id=field_tests.id and employees.id=activities.dcs_id and field_tests.id=id"
end

How do I get the result of the query?

How could I do the same query but with the ActiveRecord?

2
  • Have you setted your credentials in the config/database.yml file? Commented Jun 23, 2017 at 17:09
  • yes, I have placed the credentials Commented Jun 23, 2017 at 17:14

1 Answer 1

1

You can execute raw SQL through ActiveRecord::Base.connection but I rarely recommend it and certainly not in this case, but for edification purposes

def set_dcs
  sql= <<SQL 
      select employees.nombre, employees.apellido_paterno, employees.apellido_materno 
      from employees, activities, field_tests
      where activities.field_test_id=field_tests.id and employees.id=activities.dcs_id and field_tests.id=id
SQL 
  ActiveRecord::Base.connection.exec_query(sql)
end

I was not sure what the trailing id is in reference to and it will raise a SQL error due to it's ambiguity. I am going to assume it is a parameter and the primary search condition where as the rest are table joins.

That being said since you are using rails these can be true associations and joins resulting in far more readable controller code e.g. Model Definitions

class Employee < ActiveRecord::Base
   has_many :activities, foreign_key: :dcs_id
   has_many :field_tests, through: :activities
end 
class FieldTest < ActiveRecord::Base
   has_many :activities
end
class Activity < ActiveRecord::Base
   belongs_to :employee, foreign_key: :dcs_id
   belongs_to :field_test
end

Then the controller is simply

 Employee.
  select("employees.nombre, employees.apellido_paterno, employees.apellido_materno").
  joins(:field_tests).where(field_tests: {id: SOME_ID}) 

the resulting SQL will be similar to

 SELECT 
   employees.nombre, 
   employees.apellido_paterno, 
   employees.apellido_materno
 FROM 
   employees
   INNER JOIN activities ON employees.id = activities.dcs_id 
   INNER JOIN field_tests ON activities.field_test_id = field_tests.id
 WHERE 
   field_tests.id = SOME_ID

And this will return a collection of Employee Objects rather than an ActiveRecord::Result (returned from ActiveRecord::Base.connection.exec_query) which is more similar to an Array than anything else.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.