konnigun
konnigun

Reputation: 1805

Model methods in views

I have the following piece of code in my view:

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

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

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:
http://matthewpaulmoore.com/post/5190436725/ruby-on-rails-code-quality-checklist#instances

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.

Upvotes: 1

Views: 175

Answers (1)

Jun Zhou
Jun Zhou

Reputation: 3070

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.

Upvotes: 2

Related Questions