Question

I have two models. Hotel model:

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

User model:

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

When I signed in I'm creating hotel with some fields, after submit it's rederect me to a list of hotels and it's nice. But when I try to delete some of the hotels I get

NoMethodError in HotelsController#index

undefined method `hotels' for nil:NilClass

and after that when go to the home page(root) my session is over and user is logouted. But! Hotel was successfully destroyed. Something with index action... What i do wrong? Have any ideas?

Was it helpful?

Solution

Just add in your layouts/application.html.erb this line in a head block

<%= csrf_meta_tags %>

OTHER TIPS

The problem is that current_user is nil and failing when you try to get hotels on it.

current_user.hotels

So the question is: what sets up current_user? You're using devise - can you check what you're doing on hotels-index? do you get automatically logged in for that or does it assume you're sometimes logged-in and sometimes not and it's failing to pick that up?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top