How to use variables in your layout views?

Let’s say I wanted to find 3 products from my database and put them
in the layouts/application.rhtml view. Where do I find these 3
products? Do I just do it in application.rhtml?

<% for product in Product.find(:all, :limit => 3) %>

Because I was under the impression that you really don’t want to do
this in your views. You should do this in your controllers and pass
the result to your views. But where do I do global actions like this
in the controllers?

Thanks for your help.

Thank You,
Ben J.
E: [email protected]

I’m really not sure, but you might want to get these products in a
before_filter? That way they’ll exist no matter which controller is
using that layout.

Ben J. wrote:

Let’s say I wanted to find 3 products from my database and put them
in the layouts/application.rhtml view. Where do I find these 3
products? Do I just do it in application.rhtml?

<% for product in Product.find(:all, :limit => 3) %>

Because I was under the impression that you really don’t want to do
this in your views. You should do this in your controllers and pass
the result to your views. But where do I do global actions like this
in the controllers?

Thanks for your help.

Thank You,
Ben J.
E: [email protected]

Ben J. wrote:

Let’s say I wanted to find 3 products from my database and put them
in the layouts/application.rhtml view. Where do I find these 3
products? Do I just do it in application.rhtml?

<% for product in Product.find(:all, :limit => 3) %>

Because I was under the impression that you really don’t want to do
this in your views. You should do this in your controllers and pass
the result to your views. But where do I do global actions like this
in the controllers?

I’d put a function in application.rb

def get_3_products
Product.find(:all, :limit => 3)
end

And in the view:

<% get_3_products.each do |product| -%>
<% end -%>


– Tom M.

Ben -

Yes, you want to do the find in the controllers actions. What you
want to do is do the find in the controller action that has the same
name as the .rhtml file. So, if you are going to use index.rhtml to
display the find, then you would make an action in the controller of
that view called index. Here is some sample code:

*controller:
def index
@the_products = Product.find(:all,:limit => 3)
end

*view, index.rhtml:
<% for product in (0…@the_products.length-1) %>
<%= product.name %>
<% end %>

Hope that helps,
Ben L.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs