[英]Ruby on Rails: Common method available for controllers and views?
I have been working with Ruby on Rails for a short time. 我一直在使用Ruby on Rails很短的时间。 Recently I implemented an authentication system for my application.
最近我为我的应用程序实现了一个认证系统。 I made a method available on 'application_helper.rb' to retrieve the current logged user (method called current_user).
我在'application_helper.rb'上提供了一个方法来检索当前记录的用户(名为current_user的方法)。
The method just retrieves my User
object if the session[:user_id]
variable is present. 如果
session[:user_id]
变量存在,该方法只检索我的User
对象。
However I face the following problem. 但是我面临以下问题。
current_user
method in ' application_helper.rb ', my controllers can't make use of it current_user
方法放在' application_helper.rb '中,我的控制器就无法使用它 current_user
method in ' application_controller.rb ', my views can't make use of it current_user
方法放在' application_controller.rb '中,我的视图就无法使用它 What's the best approach to solve this problem? 解决这个问题的最佳方法是什么? The easy way would be duplicate my code in both controller and helper, but I know there is a better and more correct way.
简单的方法是在控制器和帮助器中复制我的代码,但我知道有更好更正确的方法。
Thanks in advance 提前致谢
This is a common and well-solved problem. 这是一个常见且解决得很好的问题。
Rails doesn't allow controllers to access helper methods. Rails不允许控制器访问辅助方法。 If you want to share a method between your views and controllers, you need to define the method in your controller, and then make it available to your views with
helper_method
: 如果要在视图和控制器之间共享方法,则需要在控制器中定义方法,然后使用
helper_method
使其可用于视图:
class ApplicationController < ActionController::Bbase
# Let views access current_user
helper_method :current_user
def current_user
# ...
end
end
You can pass more than one method name to helper_method
to make additional methods in your controller available to your views: 您可以将多个方法名称传递给
helper_method
以使控制器中的其他方法可用于您的视图:
helper_method :current_user, :logged_in?
def current_user
# ...
end
def logged_in?
!current_user.nil?
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.