Reputation: 372
I'm working on a ruby on rails project, and I have a really simple doubt, in a view I have something like this Food.all
, should I perform this query inside the controller and assign it to a instance variables or it is OK if I put this line inside the view.
What are the pros and cons?
I have to say I'm not doing anything else with that info.
The Food.all
its actually a select in the view.
Thanks.
Upvotes: 1
Views: 52
Reputation: 1165
The default way is to define a variable in the controller:
@foods = Food.all
Though performing queries in views is sometimes acceptable (in my opinion). It has some benefits: caching would be easier and you write less code, especially if you have a partial with this code in many places in your project. But this code is less flexible, if you need something more complex you will need to move this query. So think and choose wisely :)
Upvotes: 1
Reputation: 1250
View should only present data. Definitely better is to assign it to variable in controller and use from there.
See: How MVC works. In general view should communicate with controller, and controller with model.
Upvotes: 0