Vignesh
Vignesh

Reputation: 558

Performance impact of having queries in rails views

In Rails we usually come across cases where some queries are being fired from the Views (or even helpers). For example if I want to add a select box in my page, I would write something like;

<%= collection_select(:person, :city_id, City.all, :id, :name) %>

This example is taken right from the Rails Guides. And here we have used "City.all" instead of an instance variable. My question is, will this have any impact on the performance of my application?

Also is the following a better way of doing the same thing? And why?
In Controller:

@cities = City.all

And then in the views:

<%= collection_select(:person, :city_id, @cities, :id, :name) %>

Upvotes: 1

Views: 126

Answers (2)

Valery Kvon
Valery Kvon

Reputation: 4496

Actually there is a difference, and sometimes essential. Rendering speed (response time) depends significantly on the injected intensive queries. It can be tedious to explain why this is happening, but it's easier just to take it as a rule: design your application in that way, where the ActionView works with prepared (loaded into memory) objects.

And i think that ActionView - is a one big bottleneck of Rails (especially ERB compiling).

Upvotes: 1

LPD
LPD

Reputation: 2883

It will have no special impact on the application as such, whether its a view or a controller because for the system its just the same --> a query being issued. But its a practice that simply not encouraged, then the whole concept of code segregation and modularity goes for a toss.

I suggest the usage of an instance variable over a query in the view for this reason.

Upvotes: 1

Related Questions