无法在 rails 控制台中创建对象 - 模型关联

can't create object in rails console - model associations

我是 RoR 的新手,我正在练习模型和关联。

我创建了两个具有 belongs_to 关联的模型。当我尝试通过 Rails 控制台创建其中一个模型的对象时,我得到一个回滚事务,但我不知道为什么。我们将不胜感激!

我已成功创建用户:

=> #<User id: 1, name: "Jen", created_at: "2016-12-04 17:48:33", updated_at: "2016-12-04 17:48:33"> 

当我尝试创建一个 Post 对象时,我得到这个:

2.3.0 :012 > post = Post.create(body: "hola soy un post nuevo")
   (0.2ms)  begin transaction
   (0.1ms)  rollback transaction
 => #<Post id: nil, user_id: nil, body: "hola soy un post nuevo", created_at: nil, updated_at: nil> 

models/user.rb >

class User < ApplicationRecord
  has_many :posts
end

models/post.rb >

class Post < ApplicationRecord
  belongs_to :user
end

db/schema.rb >

ActiveRecord::Schema.define(version: 20161204174201) do

  create_table "posts", force: :cascade do |t|
    t.integer  "user_id"
    t.text     "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_posts_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

您可以轻松查看回滚背后的原因,按照以下步骤,您可以在 post 对象上调用 errors 方法。这样做

post = Post.create(body: "hola soy un post nuevo")
post.errors.full_messages

post.errors.full_messages 将 return 一个包含回滚错误的数组。将您遇到的错误粘贴到此处,我们会帮助您。

希望对您有所帮助!

Rails 5 中,presence 验证设置为 user_id,同时将帖子创建为 [=13] =].

您可以通过 config/initializers/new_framework_defaults.rb 禁用此行为:

#Require `belongs_to` associations by default. Previous versions had false.
Rails.application.config.active_record.belongs_to_required_by_default = true

您也可以使用关联中的 optional: true 选项禁用此行为:

class Post < ApplicationRecord
  belongs_to :user, optional: true
end