【问题标题】:Get error after destroy action No Method Error in Controller#index, and log out销毁操作后出现错误 Controller#index 中没有方法错误,然后注销
【发布时间】:2013-10-01 00:27:04
【问题描述】:

我有两个模型。 酒店模型:

class Hotel < ActiveRecord::Base
  attr_accessible ...
  belongs_to :user
end

用户模型:

class User < ActiveRecord::Base
  devise ...
  has_many :hotels
end

hotels_controller.rb

class HotelsController < ApplicationController
  def index   
    @hotels = current_user.hotels
  end

  def show
    @hotel = Hotel.find(params[:id])
  end

  def new
    @hotel = Hotel.new
  end

  def create
    @hotel = Hotel.new(params[:hotel])
    @hotel.user = current_user
    if @hotel.save
      redirect_to hotels_path, notice: "Nice, you added new hotel " + @hotel.title
    else
      render "new"
    end  
  end

  def edit
    @hotel = Hotel.find(params[:id])
  end

  def update
    @hotel = Hotel.find(params[:id])
    if @hotel.update_attributes(params[:hotel])
      redirect_to hotels_path, notice: "Hotel " + @hotel.title + " was successfully updated"
    else
      render "edit"
    end  
  end

  def destroy
    @hotel = Hotel.find(params[:id])
    @hotel.destroy
    redirect_to hotels_path, notice: "Hotel " + @hotel.title + " was deleted"
  end
end

当我登录时,我正在创建带有一些字段的酒店,提交后它会将我重定向到酒店列表,这很好。但是当我尝试删除我得到的一些酒店时

NoMethodError in HotelsController#index

undefined method `hotels' for nil:NilClass

然后当转到主页(root)时,我的会话结束并且用户被注销。但!酒店被成功摧毁。与索引操作有关的东西...我做错了什么?有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails devise nomethoderror


    【解决方案1】:

    只需在你的 layouts/application.html.erb 中添加这一行到 head 块中

    <%= csrf_meta_tags %>
    

    【讨论】:

      【解决方案2】:

      问题是 current_user 为 nil 并且当您尝试在其上获取酒店时失败。

      current_user.hotels
      

      所以问题是:什么设置 current_user? 您正在使用设计 - 您可以检查您在酒店索引上所做的事情吗?您是否会为此自动登录,还是假设您有时已登录,有时未登录并且无法获取该信息?

      【讨论】:

      • 在酒店索引中,我浏览酒店 获取酒店字段并添加显示/编辑/删除等按钮。用户必须登录,之后他有一个所有用户酒店的列表并且只有显示操作,当他添加新酒店时,他重新定向到仅包含他的酒店的索引操作,他可以​​显示编辑和删除它们
      • @yozzz 你真的应该检查current_user 的每一个动作;当用户注销时,索引应该是不可访问的。要寻找的另一件事是您的表单发布了一个 CSRF 令牌 - 如果它丢失并且启用了伪造保护,则用户的会话将在 DELETE 时被清除。
      • 听起来像@zetetic 在这里一针见血。如果真实性令牌丢失,您将失去会话并被注销。然后当您返回索引操作时,不会有当前用户。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多