where to put controller code for partials you render from different views in Ruby on Rails
A newbie question:
I have a partial that I'm loading on a website on different pages.
That partial needs some data, so in the controller of the parent view I do the quer开发者_StackOverflow社区y: @properties = Property.find(:all)
I pass the query results to the partial in the view using :locals
Now, I would like to render the same partial from another view. This view has a different controller. Do I have to repeat the query in that controller also? Or can I have a separate controller for partials I use one more places in the website. In this last case, how do I indicate which controller to use in the view when I put the render command?
Or should I use somethink different than partials for this kind of use?
Kind regards, Michael
How i would solve this, is to define a new file inside your lib
folder, with a meaningful name. For now i will just use does_as_shared.rb
:
module DoesAsShared
def setup_shared_data
@shared_data = ...do something useful here ...
end
end
and then inside your controllers that need that code you write:
class ThingsController < ApplicationController
include DoesAsShared
def index
setup_shared_data
.. and do some more stuff ...
end
end
The advantage of this code is that the shared code is limited to those controllers that really need it. And at the same time it is pretty readable: the include statement, given that the name is chosen well, clearly indicates what functionality is included.
You don't need to copy the code to set up the partial's data, but you would need to hoist it into a controller that your two controllers inherit from. Normally, this would be your ApplicationController
. Define a method in there that loads the data you need. For example:
class ApplicationController < ActionController::Base
# ... your code ...
protected
def load_partial_data
@properties = Property.find(:all)
end
end
Now to actually call this method you have two options:
- If all your controllers need this data, add a
before_filter
to yourApplicationController
likebefore_filter :load_partial_data
- Otherwise, add the
before_filter
to just the controllers that actually need to load the data.
I hope this helps.
精彩评论