Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put SQL queries in Rails?

What is the best practice where should I put SQL queries in Rails?

  • Should I create the methods in models for example: find_all_public_items where I'm using the find methods with all the conditions, and then using them in controllers. Like that I have all the queries in one place but I miss the flexibility that every query should be exactly suited for the need.

  • Should I just use the find/find_by_sql in controllers - like this I'm not creating thousands of methods but i'm loosing control on how the controllers are sucking data from database.

like image 376
Jakub Troszok Avatar asked Apr 29 '09 22:04

Jakub Troszok


People also ask

What is SQL injection in rails?

SQL injection is when a user is able to manipulate a value which is used unsafely inside a SQL query. This can lead to data leaks, data loss, elevation of privilege, and other unpleasant outcomes. Brakeman focuses on ActiveRecord methods dealing with building SQL statements.

What does where return in rails?

where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.


2 Answers

Put everything model-related in the model. Period.

like image 149
Sophie Alpert Avatar answered Oct 10 '22 20:10

Sophie Alpert


You should put them in your models. You might want to investigate named scopes too.

like image 27
John Topley Avatar answered Oct 10 '22 19:10

John Topley