【发布时间】:2013-11-25 07:10:45
【问题描述】:
所以在我的Items 控制器的index 视图中,我有一些对current_user 的引用。
现在,当我在未登录的情况下浏览到/items 时,出现以下错误:
NoMethodError at /items undefined method `items' for nil:NilClass
这是在我的Items#Index 在我的ItemsController.rb 中的这条线
@items = current_user.items.all
我知道这显然意味着在未登录用户上查找 items 时返回 nil 值,这自然是有道理的,因为未登录用户没有任何项目(根据应用程序的业务逻辑 - 您必须登录)。
这就是我的ability.rb 的样子:
def initialize(user)
user ||= User.new # guest user (not logged in)
alias_action :create, :read, :update, :destroy, :to => :crud
alias_action :create, :update, :destroy, :to => :cud
if user.has_role? :admin
can :manage, :all
else
cannot :cud, Item
can :read, Item
cannot :read, :items
end
if user.has_role? :seller
can :cud, Item, :user_id => user.id
can :read, Item
end
if user.has_role? :buyer
can :read, Item
end
end
与我的:admin 角色相关的if 语句的else 分支看起来如此复杂的原因是因为所有用户(无论是否登录)都应该能够查看每个项目记录(@ 987654335@)。但是,只有登录用户(任何角色)才能查看/items(即Item#index),它根据current_user 范围自定义结果。
我真的必须将该赋值语句放入我的ItemsController.rb 的if 语句中吗?
我错过了什么?
编辑 1:
这是我的顶部ItemsController.rb
class ItemsController < ApplicationController
load_and_authorize_resource
before_filter :initialize_cart
layout "item"
# GET /items
# GET /items.json
def index
#authorize! :index, @user, :message => "Rut row. Seems this door is locked and you don't have the key."
if params[:tag]
@items = current_user.items.tagged_with(params[:tag])
else
@items = current_user.items.all
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @items }
end
end
这是我的ApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :initialize_cart
rescue_from CanCan::AccessDenied do |exception|
redirect_to main_app.root_path, :alert => exception.message
end
def after_sign_in_path_for(resource_or_scope)
stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope)
end
def after_sign_out_path_for(resource_or_scope)
request.referrer
end
private
def initialize_cart
if session[:cart_id]
@cart = Cart.find(session[:cart_id])
else
@cart = Cart.create
session[:cart_id] = @cart.id
end
end
end
编辑 2:
这是我的views/items/index.html.erb
<% @items.each do |item| %>
<tr>
<td><%= link_to item.name, item_path(item) %></td>
<td><%= item.description.html_safe %></td>
<td><%= number_to_currency(item.price, precision: 2) %></td>
<% if item.is_approved? %>
<td><%= l item.approved_at, format: :custom %></td>
<% else %>
<td>N/A</td>
<% end %>
<td><%= link_to "<i class='fa fa-edit'></i>".html_safe, edit_item_path(item) %></td>
<td><%= link_to "<i class='fa fa-trash-o'></i>".html_safe, item, method: :delete, data: { confirm: "Are you sure you want to delete #{item.name}?" } %></td>
</tr>
<% end %>
【问题讨论】:
-
你能把输出@items的部分放到html.erb中吗?
-
角色是什么,只有 :admin、:buyer 和 :seller?更新了我的答案。检查能力逻辑。
-
@SteveWilhelm 是的,只是这三个角色。
-
@JoseRamonCamacho 刚刚更新了问题。
标签: ruby-on-rails ruby-on-rails-3 devise cancan