views:

92

answers:

4

In my rails application, I render a partial on multiple pages, and in that partial is a variable. So currently, lets say I have 5 pages that render :partial => "partialname", and inside of partialname is @variable.

Can I have it so that partialname has its own action with @variable instantiated inside, rather than having @variable be called 5 times from each action that renders the partial?

Thanks!

A: 
klochner
actually, that might work as a solution!
Jess
you should escape model.variable, just change that to <%=h model.variable %>
Oliver N.
right, thanks - amended.
klochner
A: 

So, is this a problem of code running 5 times per request that you'd rather not? Like, you've got a partial and in it is:

@my_var = MyModel.some_expensive_method

If so, you could just cache the result in the model:

def cached_some_expensive_method
  @some_expensive_method ||= some_expensive_method()
end
+2  A: 

I would create a before_filter on all the methods that need the common behavior.

But if you really want the partial to have its own "action," make a helper method that does whatever "action-y" things you want and then renders the partial. That works out to essentially the same thing. I've done this before to make a template-type partial that contains various pieces of data that need processing.

Chuck
+1  A: 

http://stackoverflow.com/questions/704687/rails-sub-controllers/1109088#1109088

See my answer on this.

Very similar method here, using before filters either using controller inheritance or modules when needed.

Omar Qureshi