I need to access multiple models from a single view. Previously, my links_controller was only used to provide link resources sorted in different ways. Now I would like to include a partial (I’m assumning) which shows the top users sorted by score (@users = User.all.sort_by(&:score))
I’m aware that I could plug this code into every link action and access it from the view but this doesn’t seem to be the “ruby way” and I will need to access more models in the near future. This could get really dirty, are there any techniques for this situation?
Notes:
- I see my application going in the direction of having a single format with dynamic page contents, in essence, a typical web app.
- I’m aware of before_filter but this seems cumbersome, considering the direction that I would like the application to go in. Eventually accessing several models from any view.
This sort of thing is best encapsulated as a helper method that’s exercised by that particular partial. For instance if this was your partial
_user_listing.html.erb:Then you’d implement the
users_by_scoremethod in a helper file included by all the relevant controllers, or ApplicationHelper if it’s that prevalent:In other MVC systems this would be considered a sub-view with its own controller, but in Rails the best you can do is to have helper methods.