ruby-on-rails – 我的控制器中的帮助方法
发布时间:2020-12-16 21:40:01 所属栏目:百科 来源:网络整理
导读:我的应用程序应该呈现html,以便在用户点击ajax-link时回答. 我的控制器: def create_user @user = User.new(params) if @user.save status = 'success' link = link_to_profile(@user) #it's my custom helper in Application_Helper.rb else status = 'err
我的应用程序应该呈现html,以便在用户点击ajax-link时回答.
我的控制器: def create_user @user = User.new(params) if @user.save status = 'success' link = link_to_profile(@user) #it's my custom helper in Application_Helper.rb else status = 'error' link = nil end render :json => {:status => status,:link => link} end 我的帮手: def link_to_profile(user) link = link_to(user.login,{:controller => "users",:action => "profile",:id => user.login},:class => "profile-link") return(image_tag("/images/users/profile.png") + " " + link) end 我试过这样的方法: ApplicationController.helpers.link_to_profile(@user) # It raises: NoMethodError (undefined method `url_for' for nil:NilClass) 和: class Helper include Singleton include ActionView::Helpers::TextHelper include ActionView::Helpers::UrlHelper include ApplicationHelper end def help Helper.instance end help.link_to_profile(@user) # It also raises: NoMethodError (undefined method `url_for' for nil:NilClass) 另外,是的,我知道关于:helper_method,它的作品,但我不想重载我的ApplicationController与大量的方法 解决方法
冲.让我们回顾一下您需要访问defint函数/方法,但不希望这些方法被附加到当前对象.
所以你想做一个代理对象,这将代理/委托给这些方法. class Helper class << self #include Singleton - no need to do this,class objects are singletons include ApplicationHelper include ActionView::Helpers::TextHelper include ActionView::Helpers::UrlHelper include ApplicationHelper end end 而在控制器中: class UserController < ApplicationController def your_method Helper.link_to_profile end end 这种方法的主要缺点是,从助手功能中,您将无法访问控制器上下文(EG,您将无法访问参数,会话等) 妥协是将这些函数声明为辅助模块中的私有功能,因此,当您将包含模块时,它们也将在控制器类中是私有的. module ApplicationHelper private def link_to_profile end end class UserController < ApplicationController include ApplicationHelper end ,正如Damien指出的. 更新:您获得“url_for”错误的原因是您无法访问控制器的上下文,如上所述.您可以强制传递控制器作为参数(Java-style;)),如: Helper.link_to_profile(user,:controller => self) 然后,在你的帮手中: def link_to_profile(user,options) options[:controller].url_for(...) end 或事件更大的黑客,提交here.但是,我会推荐解决方案,使方法私有,并包括在控制器. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |