首页 > 解决方案 > 我的rails应用程序中的nil:NilClass的未定义方法`jobs'

问题描述

请各位,我需要帮助解决这个问题。我试图找到工作/新的。从我的 Rails 控制台;

NoMethodError - undefined method `jobs' for nil:NilClass:
  app/controllers/jobs_controller.rb:17:in `new'

路线.rb

Rails.application.routes.draw do
  resources :jobs
  devise_for :users
    resources :home
    root 'jobs#index'
  end

作业控制器.rb

 # GET /jobs/new
  def new
    @job = current_user.jobs.build
  end

  # POST /jobs
  # POST /jobs.json
  def create
    @job = current_user.jobs.build(job_params)

    respond_to do |format|
      if @job.save
        format.html { redirect_to @job, notice: 'Job was successfully created.' }
        format.json { render :show, status: :created, location: @job }
      else
        format.html { render :new }
        format.json { render json: @job.errors, status: :unprocessable_entity }
      end
    end
  end

标签: ruby-on-railsruby

解决方案


我没有添加 before_action :authenticate_user!在jobs_controller 中。

我添加了它,它现在正在工作:

# jobs_controller
class JobsController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show]

  # stuffs
  def method
  end

  def method
  end
end

推荐阅读