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.
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.
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.
Put everything model-related in the model. Period.
You should put them in your models. You might want to investigate named scopes too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With