开发者

What is the best practice for rendering the same thing in two different ways?

I got a - say Actor - model and the relative controller with a classical show action that displays the complete list of actors and various information about them (e.g. movies they've starred in, etc.).

Now, I'd like to retrieve the exact same information I need for my show action, but to show them in a partial with a different style, since this partial - say _search_results - has to be used to create a small "search-as-you-type" box.

Imagine the show action as a Fi开发者_如何学JAVAnder window displaying folders and files and my partial as the dropdown list that appears when you search something on Spotlight.

Of course I would like to stay as DRY as possible and so I'm wondering what is the best practice to do this, while almost not repeating code in my actors_controller, since the information needed by the partial are exactly the same that the show action already produces for the show view.

Thanks.

Edit (N.B.) Of course I want the partial to be rendered from inside the controller, because I don't want all my application layout to be shown in the search result box!


The classic advice on this is to stick the information assembly in the model, so it can be accessed by multiple controller actions without duplication. Named scopes and the like make much of this easy to do.

http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model


You want to use a Presenter. It is a class that encapsulates all the logic needed to prepare the data for the template/partial you are using. Then you can create an instance of that presenter in your controller before you render the template. Here is a good write up about the Presenter pattern and when to use it.

http://kpumuk.info/ruby-on-rails/simplifying-your-ruby-on-rails-code/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜