Fred wrote:
For instance, let’s assume I’d like to have statistics regarding usage
in div1, an rss feed in div3, some other data in div4, and then my real
action result in div2, what would be the best way to do this?
There are several aspects to this question. The main ones to look at
are the View and the Controller.
A Controller’s action is just the routine which provides the business
logic for the View. If you want to have statistics, RSS feed, and other
data in a single View, then the bottom-line simplest way to do it is to
call all that business logic in the single action. Then you put all the
display logic in the various DIVs located in your single View.
To make this more DRY, you can abstract the specific parts of the
business logic into different methods, either controller methods ,helper
methods or components. You can also abstract the View into multiple
partial templates.
So in your controller’s “view” directory, you might have
_statistics.rhtml, _rss.rhtml, and _otherdata.rhtml.
Then you could make either a helper or a controller method called
“statistics” and “rss”, and call them from your main action:
data_controller.rb:
class DataController < ApplicationController # whatever yours is called
def index # again, whatever specific controller you call to show the
page
@statistics = self.generate_statistics()
@rss_feeds = self.generate_rss()
end
… other methods, actions, etc
end
Then in your View you might call the partials:
index.rhtml:
Today's statistics:
<% render :partial => "statistics" %>
Your feeds:
<% render :partial => "rss_feeds" %>
And since you have an instance variable called @statistics, it’s sent to
the partial of the same name as a local variable. So within your
partial “statistics”, you could do this:
_statistics.rhtml:
Total number of entries: <%= statistics.total_entries %>
Total logins: <%= statistics.total_logins %>
Most recent login: <%= statistics.most_recent_login %>
... etc.
If “statistics” isn’t a simple object but you’ve got a few variables you
need to refer to in your partial, you can call them by sending the
:locals parameter (assuming these instance variables are set in your
original controller):
(in index.rhtml:)
render :partial => “statistics”, :locals => {
:total_entries => @total_entries,
:total_logins => @total_logins,
:most_recent_login => @most_recent_login }
It’s the controller’s job to assemble all the data you need for your
view, regardless of which models or other sources that data comes from.
So it’s not a question of putting “data from multiple controllers” into
your view, it’s a question of making sure the controller in question
gets the data together where you can use it.
(components, apparently, are strongly advised against, even in the
official documentation)
Are they? By whom? Just curious, because I’ve used them seldom myself
but hadn’t noticed this advice personally.
Hope this helps!
Jeff