Model methods in views

I have the following piece of code in my view:

<% if @user.get_products.any? %>
  <%='products', @user.get_products.collect { |user| [,]}) %>

Where get_products is making an ActiveRecord query to DB. So I wonder if it actually does two same queries or uses cached result from first querie on second call? I tried to check it in server logs - but found nothing. I would also like to know if I can control this behavior somehow, i.e. set/unset cache for this view. Thanks!

UPDATE: I think it violates MVC too, but what confused me was IDE warning: "view should not share more than two variables with controller." However, I am creating somewhat "one page" website, so I need to have @user, @nearest_users, and @user_products in the same view. So I found the following article: which said

Only one or two instance variables are shared between each controller and view.

Instance variable hell - when a lot of instance variables are shared between a controller and a view - is easy to do in Rails. It’s also potentially dangerous to performance, because you can end up making duplicate calls on associations unknowingly. Instead, your controller should only manage one instance variable - and perhaps a second for the current_user. That way, all calls to associations are loaded “on demand”, and can be instance-variable-cached in a single place.

This methodology also works out well for fragment caching, because you can check caches in views before actually loading associations.

For example, instead of having your Blog controller create an instance variable for both @post and @related_posts, just make a single method, @post, and give your Post model a related_posts method, so you can just call @post.related_posts in your views.


To answer your question: Queries in view don't get cached.

What's more, Ruby codes in ERB template are executed using eval, which is very inefficient.

So my advice is: avoid writing logic in view, it's kind of bad practice.

Need Your Help

Is there any performance difference in using .resx file and satellite assembly?

.net localization

Which is the best way to go forward while building a localized aspx web application, .resx files of satellite assemblies? Is there any performance comparisons available any where on web?

Use ALFA in standalone mode

authorization xacml alfa abac

The DSL ALFA by Axiomatics is only provided as an eclipse plugin. Is it possible to use it in standalone mode? There is a Main class bundled in the jar but I have had no luck getting it to work.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.