SNov SNov - 1 year ago 99
Ruby Question

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| [,]}) %>

is making an
query to DB. So I wonder if it actually does two same queries or uses cached result from first query 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.



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
, and
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download