2

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

3
  • What route did you follow? Is there a way to retrieve that array of top 5 foobars in the application controller and then use it wherever you like? Commented Sep 19, 2012 at 3:28
  • No unfortunately not - like Michal said, it really should be the controller which makes the decisions about what should be displayed on the view Commented Sep 19, 2012 at 8:34
  • possible duplicate of how do i write action methods for partial views? Commented Feb 9, 2013 at 22:26

2 Answers 2

5

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?

Sign up to request clarification or add additional context in comments.

2 Comments

This answer would have been so helpful this time last year!!
Haha no worries, better late than never :D
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.