我目前在 Rails 中从事一个爱好项目,偶然发现了一个我认为是 Rails 中的常见问题。我已经阅读了几章和一个 Lynda 教程,但我还没有找到任何解决这个问题的最佳实践。也许在线社区可以帮助我。
在我的 application.html.erb 中,我添加了以下代码:
<!DOCTYPE html>
<html>
<head>
<title>SioMeny</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<div id="wrapper">
<header>
<h1>SiO Menysystem</h1>
</header>
<div id="site_menu">
<%= render :partial => "shared/admin_menu" if admin_logged_in? %>
<%= render :partial => "shared/user_menu" if logged_in? %>
<%= render :partial => "shared/site_menu" %>
</div><!-- div#site_menu -->
<div id="main">
<%= render :partial => "shared/flash", :locals => {:flash => flash} unless flash.nil? %>
<%= yield %>
</div>
</div><!-- div#wrapper -->
</body>
</html>
我的问题始于#site_menu 和不同部分的加载。我在这里尝试实现的是根据用户可能拥有的权限扩展的菜单。登录?和admin_logged_in?位于 application_controller 中。
class ApplicationController < ActionController::Base
protect_from_forgery
def login_required
unless logged_in?
flash[:notice] = "Du må være logget inn for å se denne siden"
redirect_to :controller => "user", :action => "login"
end
end
def admin_required
unless admin_logged_in?
flash[:notice] = "Du må være logget inn som administrator for å se denne siden"
redirect_to :controller => "user", :action => "login"
end
end
def logged_in?
if session[:user_id]
return true
end
return false
end
def admin_logged_in?
if logged_in?
user = User.find_by_id[:user_id]
if user.is_admin?
return true
end
end
return false
end
end
此时我收到一个错误:
ArgumentError in Site#index
Showing /Users/ola/Documents/Coding/SioMeny/app/views/layouts/application.html.erb where line #15 raised:
wrong number of arguments (0 for 1)
Extracted source (around line #15):
12: <h1>SiO Menysystem</h1>
13: </header>
14: <div id="site_menu">
15: <%= render :partial => "shared/admin_menu" if admin_logged_in? %>
16: <%= render :partial => "shared/user_menu" if logged_in? %>
17: <%= render :partial => "shared/site_menu" %>
18: </div><!-- div#site_menu -->
Rails.root: /Users/ola/Documents/Coding/SioMeny
非常欢迎任何帮助!我还尝试让两个logged_in函数设置一个实例变量,该变量是在视图中检查的布尔类型,这有效,但并非一直有效,因为它们取决于它们的设置时间。我还尝试在帮助程序中创建类似的方法并从视图中调用它们,但这也不起作用。