我有两个模型。酒店型号:
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
之后,当转到主页(根)时,我的会话结束并且用户被注销。但!酒店被成功摧毁。与索引操作有关的东西...我做错了什么?有什么想法吗?