nil:NilClass的未定义方法“ courses”

时间:2019-02-24 14:33:22

标签: ruby-on-rails ruby

当我在heroku应用程序上访问课程/新页面时,出现错误,提示未定义方法课程。另外,当我在控制台上创建课程时,它没有ID或created_at。

课程控制器:

class CoursesController < ApplicationController
  def home
    @course = current_user.courses.find(params[:id])
  end

  def new
    @course = current_user.courses.build
  end

  def create
    @course = current_user.courses.build(course_params)
    if @course.save
      flash[:success] = "Course Created"
      redirect_to coursehome_path
    else
      render 'new'
    end
  end

  private

    def course_params
     params.require(:course).permit(:name)
    end
end

大学模式:

class College < ApplicationRecord
  has_many :courses, dependent: :destroy
  has_secure_password
  def College.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? 
    BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end
end

课程模式:

class Course < ApplicationRecord
  belongs_to :college
end

迁移:

class CreateCourses < ActiveRecord::Migration[5.1]
  def change
    create_table :courses do |t|
      t.string :name
      t.references :college, foreign_key: true

      t.timestamps
    end
    add_index :courses, [:college_id, :created_at]
  end
end

编辑:

实际上,我创建了一个名为collegesessions的控制器,并在其助手中添加了current_user方法:

module CollegesessionsHelper
  def log_in(college)
    session[:user_id] = college.id
  end

  def current_user
    if session[:user_id]
      @current_user ||= College.find_by(id: session[:user_id])
    end
  end

  def logged_in?
    !current_user.nil?
  end

 def log_out
    session.delete(:user_id)
    @current_user = nil
  end
end

1 个答案:

答案 0 :(得分:2)

当您尝试访问时 current_user.courses,它会在user模型中寻找课程关联。

您的课程模型没有user关联。

课程模式

class Course < ApplicationRecord
  belongs_to :college
  belongs_to :user
end

用户模型

class User < ApplicationRecord
    //fields

    has_many: courses

end