Rails DRY 问题:控制器和视图中需要相同的代码
我的页面中有以下登录检查:
class LoungeController < ApplicationController
before_filter :confirm_logged_in
def index
end
end
同时在此处定义了 confirm_logged_in
:
class ApplicationController < ActionController::Base
protect_from_forgery
protected
def confirm_logged_in
return true if current_user
redirect_to(:controller => 'access', :action => 'login')
return false # halts the before_filter
end
def current_user
return false unless session[:user_id]
user = User.find(session[:user_id])
return false unless user
(user.display_name == session[:user_display_name]) ? user : nil
end
end
现在,我想在 app/views/layouts/application.html 中也使用
:confirm_logged_in
.erb
<% if confirm_logged_in %>
<div id="logged_in_as">You are logged in as <%= session[:user_display_name] %></div>
<div id="logout"><%= link_to("Logout", {:controller => "access", :action => "logout"}, :id => "logout_link") %></div>
<% end %>
您建议如何解决这个问题?我应该在哪里定义 confirm_logged_in
?
I have the following login check in my page:
class LoungeController < ApplicationController
before_filter :confirm_logged_in
def index
end
end
while confirm_logged_in
defined here:
class ApplicationController < ActionController::Base
protect_from_forgery
protected
def confirm_logged_in
return true if current_user
redirect_to(:controller => 'access', :action => 'login')
return false # halts the before_filter
end
def current_user
return false unless session[:user_id]
user = User.find(session[:user_id])
return false unless user
(user.display_name == session[:user_display_name]) ? user : nil
end
end
Now, I want to use confirm_logged_in
also in app/views/layouts/application.html.erb
:
<% if confirm_logged_in %>
<div id="logged_in_as">You are logged in as <%= session[:user_display_name] %></div>
<div id="logout"><%= link_to("Logout", {:controller => "access", :action => "logout"}, :id => "logout_link") %></div>
<% end %>
How would you suggest to solve this problem ? Where should I define confirm_logged_in
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
helper_method
controller.rb
You can use
helper_method
controller.rb