我为User
和Course
逻辑代码设置了正确的逻辑。以下是我目前拥有的文件:
应用/模型/ course.rb :
class Course < ApplicationRecord
belongs_to :user
validates_presence_of :course
end
app / models / user.rb (使用Devise):
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
分贝/迁移/ ... 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)
应用/控制器/ 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
在模型创建过程中是否存在遗漏或完全混淆的内容?
答案 0 :(得分:1)
如果没有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