Reputation: 6897
In our Rails 4 app, there are four models:
class User < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :calendars, through: :administrations
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
class Calendar < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :users, through: :administrations
end
Here is our AdministrationsController
:
class AdministrationsController < ApplicationController
def to_s
role
end
def index
@user = current_user
@administrations = @user.administrations
@calendar = Calendar.new
end
def show
@administration = Administration.find(params[:id])
end
def destroy
Administration.find(params[:id]).destroy
flash[:success] = "You successfully quit this calendar"
redirect_to dashboard_path
end
end
When a new user
signs up, ie: a new @user is created, he is redirected to his dashboard
, which corresponds to the Administration
index.html.erb
view:
<% provide(:title, 'Dashboard') %>
<h1>Dashboard</h1>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<% if @user.administrations.any? %>
<h2>My Calendars</h2>
<table>
<%= render @administrations %>
</table>
<% end %>
<section class="calendar_form">
<%= render 'shared/calendar_form' %>
</section>
</div>
</div>
</div>
At this moment, a user has no calendar and no administration.
So, logically, after we sign up a new user, we get the following error:
NoMethodError in AdministrationsController#index
undefined method `administrations' for nil:NilClass
def index
@user = current_user
@administrations = @user.administrations
@calendar = Calendar.new
end
We tried to do something like:
def index
@user = current_user
@administrations = @user.administrations if @user.administrations.exists?
@calendar = Calendar.new
end
but it did not work, and returned a similar error.
How can we fix this?
Upvotes: 0
Views: 975
Reputation: 4604
the problem is that current_user
is returning nil
, not a user object. Maybe you have created a user but not logged in.
Upvotes: 2
Reputation: 4821
you can utilize the #respond_to?
method
@administrations = @user.administrations if @user.respond_to? :admininstrations
Upvotes: 0