创建新的模型对象时,用户 ID 不被拾取

User ID does not pick up when creating a new model object

我已经为 UserCourse 逻辑代码设置了正确的逻辑。这是我目前拥有的文件:

app/models/course.rb:

class Course < ApplicationRecord
  belongs_to :user
  validates_presence_of :course
end

app/models/user.rb(使用设计):

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :omniauthable
  has_many :courses
end

db/migrate/...create_courses.rb:

class CreateCourses < ActiveRecord::Migration[5.0]
  def change
    create_table :courses do |t|
      t.string :course, limit: 300
      t.text :description
      t.string :location
      t.references :user, foreign_key: true

      t.timestamps
    end

    add_index :courses, :course, unique: true
    add_index :courses, :description
  end
end

当我为 course 创建一个新对象时,我得到以下输出:

1 个错误禁止保存这篇文章:

问题的堆栈跟踪:

Started POST "/courses" for 75.108.207.135 at 2016-07-22 22:33:28 -0500
Cannot render console from 75.108.207.135! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by CoursesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"+RSKtrUI2jQ5DcXcndw7Lb9PN+mi6FJxGC3zX8oBLTnZdFeUTzTgZGc84V7onkW2UeNPTO2pHJ9cV2vx9yLjFQ==", "course"=>{"course"=>"Hello world", "description"=>"Hi", "location"=>"Hi"}, "commit"=>"Add Course"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 2], ["LIMIT", 1]]
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
  Rendering courses/new.html.erb within layouts/application
  Rendered courses/new.html.erb within layouts/application (2.1ms)
  Rendered layouts/_nav.html.erb (3.0ms)
Completed 200 OK in 181ms (Views: 176.4ms | ActiveRecord: 0.5ms)

app/controllers/courses_controller.rb:

def create
    @course = Course.new(course_params)

    respond_to do |format|
      if @course.save
        format.html { redirect_to @course }
        format.json { render :show, status: :created, location: @course }
      else
        format.html { render :new }
        format.json { render json: @course.errors, status: :unprocessible_entity }
      end
    end
  end

我在创建模型的过程中遗漏了什么或完全搞砸了吗?

如果没有 CourseController#create 方法,很难确切地知道发生了什么 -- 但您想要做的是使用 has_many 添加到用户对象的方法之一。

大意为:

user.courses.build(params[:course])user.course.create(params[:course])

构建和创建都可以从集合中获得。

当然,Rails 指南有更多信息:http://guides.rubyonrails.org/association_basics.html#the-has-many-association