ruby on rails是放置布局数据库代码(公共数据库调用)的最佳位置



我正在rails中制作一个控制面板(用户帐户)。在布局中,我需要显示消息或通知(类似facebook的风格)。问题是这些东西需要访问数据库,我不确定把这些代码放在哪里,因为它与控制器无关,但布局与多个控制器共享。

那么,从数据库中获取消息的代码最好放在哪里呢?我应该放在布局中(我认为这不对),还是作为助手?

最好的解决方案是构建一个控制面板控制器,用于处理身份验证和权限,并从数据库加载常见的用户数据,如消息。。。这是一个示例代码

class ControlPanelController < ApplicationController
  before_filter :authenticate_user!
  before_filter :get_user_data
  helper_method :mailbox
  authorize_resource
  protected
  def get_user_data
    @header_conversations=mailbox.inbox.limit(3)
    @uevents= Event.scoped
    @uevents= @uevents.after(Time.now)
  end
  def mailbox
    @mailbox ||= current_user.mailbox
  end
end

然后我的web应用程序中的所有类都扩展了这个类:)

我发现一种方法是使用before_filter。通过在ApplicationController中定义过滤器(以便您可以从任何控制器访问它)。

class ApplicationController < ActionController::Base
 # ..
protected
def load_messages
  @messages = Message.all 
end
end

然后在任何控制器中:

class FooController < ApplicationController
before_filter :load_messages
  def index
  #  @messages is set
  end
end

最新更新