新手问题 ApplicationHelper 和 ApplicationController 的用法区别

n00b1 · 2014年08月19日 · 最后由 jzlikewei 回复于 2014年08月19日 · 3889 次阅读

有两个小白问题希望得到大家的指点:

1、ApplicationHelper 和 ApplicationController 的用法区别

我看两个地方都是用于放一些常用/复用代码的,譬如在 ApplicationHelper 中

module ApplicationHelper
  # Returns the full title on a per-page basis.
  def full_title(page_title)
    base_title = "Ruby on Rails Tutorial Sample App"
    if page_title.empty?
      base_title
    else
      "#{base_title} | #{page_title}"
    end
  end
end

而 ApplicationController 中

def current_user
  User.find(session[:user_id]) if session[:user_id]
end

为了这段代码能在 view 中使用,所以还要加一句helper_method :current_user

那我的理解是不是 ApplicationHelper 中放的是 view 中可复用的方法,而 ApplicationController 中的是 controller 中可复用的方法?

第二个问题是每次用 rails g controller 都会自动生成一个对应的 helper,但貌似一般都不怎么会用到它们,要么直接放 ApplicationHelper 或者 ApplicationController,如何 generate 能不生成多余的 helper 呢

关于不自动生成 helper,请到 rails guides 的首页相应的地方找文档。

Controller 的 action 代码的末尾,如果你没有调用 render 或者 redirect_to,它会自动调用 render 方法,并根据约定找到相应的模板,并新建一个 view 实例,我自己称为 view context,最后 response 的内容是有 view context 直接输出的,而不是 controller,记住 rails 是一个 rack app,如果你看过源码你就会知道 controller 的 action 最后其实被包装成了一个 middleware,所以我自己认为 router 并不是 end point,controller 的 action 才是 end_point,仅仅是个人理解,对于 http request 的 response 内容就是由这个 action middleware 返回的

而为什么 Helper 能在 view 里面直接用,是因为 helper 里面的方法会被载入到 view context 里去,故在 view 中能直接用。

而 ApplicationController 并不会被加载进 view context,但是 rails 提供了 helper_method 让你可以将某个方法载入到 view context。

另外,如果你想在 action 访问 view context 的话,你可以在 action 里直接使用 view_contexthttp://apidock.com/rails/AbstractController/Rendering/view_context

对,ApplicationHelper 和 ApplicationController 在我的理解上其实就是逻辑的区别

需要 登录 后方可回复, 如果你还没有账号请 注册新账号