What is the best practice where should I put SQL queries in Rails?
我应该在Rails中放置SQL查询的最佳实践是什么?
-
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.
我应该在模型中创建方法,例如:find_all_public_items,其中我使用了具有所有条件的find方法,然后在控制器中使用它们。就像我在一个地方有所有的查询,但我错过了每个查询应该完全适合需要的灵活性。
-
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.
我应该只在控制器中使用find / find_by_sql - 这样我就不会创建数以千计的方法,但是我无法控制控制器如何从数据库中提取数据。
2 个解决方案
#1
You should put them in your models. You might want to investigate named scopes too.
你应该把它们放在你的模型中。您可能也想调查命名范围。
#2
Put everything model-related in the model. Period.
将模型相关的所有内容放在模型中。期。
#1
You should put them in your models. You might want to investigate named scopes too.
你应该把它们放在你的模型中。您可能也想调查命名范围。
#2
Put everything model-related in the model. Period.
将模型相关的所有内容放在模型中。期。