NilClass的未定义方法

时间:2014-04-17 00:50:15

标签: ruby-on-rails methods undefined null

目前,我收到以下错误:

NoMethodError in EventsController#create
undefined method `events' for nil:NilClass

以下是以下文件...... EventsController。我省略了一些方法。包括Events#new

class EventsController < ApplicationController
  include SessionsHelper

  def create
    @event = current_user.events.build(event_params)
    if @event.save
        flash[:success] = "You created an event"
        redirect_to events_path
    else
        redirect_to new_event_path
    end
  end

  private

def event_params
    params.require(:event).permit(:description)
end
end

SessionsHelper 包含current_user ...我已在此处发布了整个文件以防万一。

module SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attributes(remember_token: User.hash(remember_token))
    self.current_user = user
  end

  def current_user
    remember_token = User.hash(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
  end

  def current_user=(user)
    @current_user = user
  end

  def sign_out
    current_user.update_attributes(remember_token: 
            User.hash(User.new_remember_token))
    cookies.delete(:remember_token)
    self.current_user = nil
  end

  def signed_in?
    !current_user.nil?
  end
end

最后,这是Events#new。这是调用Events#create操作的视图:

<h1>Events#new</h1>

<!-- url: will send all form data to the action specified -->

<%= form_for(:event, url: {action: "create"}) do |f| %> 

    <%= f.label "Description" %>
    <%= f.text_area :description, value: "Write here" %><br>

    <%= f.submit "Create event" %>

<% end %>

1 个答案:

答案 0 :(得分:0)

没关系,所需要的只是更新服务器。关闭服务器并键入rails s。