before_filter to set common instance variable (Ruby On Rails)
Is it a common practice to do a filter like this:
before_filter :get_clients, :only => [:new, :edit, :create, :update]
...
def get_clients
@clients = Client.accessible_by(current_ability)
end
My form needs access to @client开发者_如何学Pythons, so I setup the variable @clients with a before filter instead of doing it in every method. Does this make sense?
I'd recommend building a memoized helper instead:
def current_clients
@current_clients ||= Client.accessible_by(current_ability)
end
helper :current_clients
This will work just as well as a before-filter, but won't be run unless you need to actually load the client list for a form/view. You're getting lazy loading of this resource. The responsibility for knowing how to load the list of clients still remains with the controller.
精彩评论