Rails 4: <Model>Controller#index 中的 NoMethodError

Rails 4: NoMethodError in <Model>Controller#index

在我们的Rails4 app中,有四种模式:

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

这是我们的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

当一个新的 user 注册时,即:创建一个新的@user,他被重定向到他的 dashboard,对应于 Administration index.html.erb查看:

<% 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>

此时用户没有日历也没有管理。

因此,从逻辑上讲,在我们注册新用户后,我们会收到以下错误:

NoMethodError in AdministrationsController#index

undefined method `administrations' for nil:NilClass

def index
  @user = current_user
  @administrations = @user.administrations
  @calendar = Calendar.new
end

我们尝试做类似的事情:

def index
  @user = current_user
  @administrations = @user.administrations if @user.administrations.exists?
  @calendar = Calendar.new
end

但是没有成功,返回了类似的错误。

我们该如何解决这个问题?

你可以利用#respond_to?方法

@administrations = @user.administrations if @user.respond_to? :admininstrations

问题是 current_user 正在返回 nil,而不是用户对象。也许您已经创建了一个用户但还没有登录。