开发者

before_filter to set common instance variable (Ruby On Rails)

开发者 https://www.devze.com 2023-02-14 11:56 出处:网络
Is it a common practice to do a filter like this: before_filter :get_clients, :only => [:new, :edit, :create, :update]

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.

0

精彩评论

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