【发布时间】:2016-07-23 03:54:36
【问题描述】:
我已经为User 和Course 逻辑代码设置了正确的逻辑。以下是我目前拥有的文件:
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
我在创建模型的过程中是否遗漏了什么或完全搞砸了?
【问题讨论】:
-
为什么您的课程模型中的验证会验证课程的存在?课程是对象,而不是对象的领域。你不应该验证用户的存在吗?
-
请添加课程创建方法
-
Course validates_presence_of :course- wtf?
标签: ruby-on-rails activerecord ruby-on-rails-5