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

时间:2015-07-09 18:14:24

标签: ruby-on-rails ruby-on-rails-4 model-view-controller nomethoderror

在我们的Rails 4应用程序中,有四种模式:

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

我们试图做类似的事情:

using (var command = CreateCommand("uspGetAllNumericUnits", CommandType.StoredProcedure))
        {
            using (var connectionScope = command.Connection.CreateConnectionScope())
            {
                using (var reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            ....
                        }
                    }
                }
            }
        }   

但它没有用,并返回了类似的错误。

我们如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以使用#respond_to?方法

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