Jordan Wallwork
Jordan Wallwork

Reputation: 3114

Rails render partial (with action code)

Is there a way to render a partial view with accompanying code in rails?

For instance: I want to be able to create a partial view which will show the top 5 foobars on my site. This partial needs accompanying code to retrieve some foobars from the database, rank them according to an algorithm, and then output the view with the top 5.

I want to be able to include this partial on any page I fancy, preferably just by using something like

<%= render :action => "top_five_foobars" %>

Is this doable? I'm used to asp.net mvc where you can create an action that runs some code and returns a partial, but it seems like in rails it returns simply the template...

Upvotes: 2

Views: 1517

Answers (2)

fotanus
fotanus

Reputation: 20116

If google get you here, you might be looking for cells

Cells are view components for Rails. They are mini-controllers with their own MVC stack, can invoke logic and render views. They bring back OOP to Rails' view layer and make writing reusable portlets for your applications fun.

You need something like a shopping cart, which appears on almost every page of your app.

You wouldn't use a partial and a helper, would you?

Upvotes: 5

Carlos Blanco
Carlos Blanco

Reputation: 8762

It might not be the cleanest way, but what I did is that I created a helper method in the Application Controller that retrieves the top 5 foobars. Then I call this method in the views. I also cached the part of the view that shows the results.

Upvotes: 2

Related Questions