Mis*_*hko 14 ruby-on-rails ruby-on-rails-3 content-tag
在我的Rails 3应用程序中,我使用Ajax来获取格式化的HTML:
$.get("/my/load_page?page=5", function(data) {
alert(data);
});
class MyController < ApplicationController
def load_page
render :js => get_page(params[:page].to_i)
end
end
Run Code Online (Sandbox Code Playgroud)
get_page使用该content_tag方法,也应该可用app/views/my/index.html.erb.
由于get_page使用了许多其他方法,我将所有功能封装在:
# lib/page_renderer.rb
module PageRenderer
...
def get_page
...
end
...
end
Run Code Online (Sandbox Code Playgroud)
并包括它:
# config/environment.rb
require 'page_renderer'
# app/controllers/my_controller.rb
class MyController < ApplicationController
include PageRenderer
helper_method :get_page
end
Run Code Online (Sandbox Code Playgroud)
但是,由于该content_tag方法不可用app/controllers/my_controller.rb,我收到以下错误:
undefined method `content_tag' for #<LoungeController:0x21486f0>
Run Code Online (Sandbox Code Playgroud)
所以,我试图添加:
module PageRenderer
include ActionView::Helpers::TagHelper
...
end
Run Code Online (Sandbox Code Playgroud)
但后来我得到了:
undefined method `output_buffer=' for #<LoungeController:0x21bded0>
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么 ?
你怎么解决这个问题?
Noz*_*Noz 33
为了回答提出的问题,ActionView :: Context定义了output_buffer方法,解决错误只需包含相关模块:
module PageRenderer
include ActionView::Helpers::TagHelper
include ActionView::Context
...
end
Run Code Online (Sandbox Code Playgroud)
助手实际上是视图代码,不应该在控制器中使用,这解释了为什么它如此难以实现。
另一种(恕我直言,更好)方法是使用您想要围绕 params[:page].to_i 的 HTML 构建视图或部分视图。然后,在控制器中,您可以使用 render_to_string 在 load_page 方法末尾的主渲染中填充 :js 。然后你就可以扔掉所有其他东西,它会变得更加干净。
顺便说一句,helper_method 的作用与您想要做的相反 - 它使控制器方法在视图中可用。
| 归档时间: |
|
| 查看次数: |
8829 次 |
| 最近记录: |