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

cat*_*h22 1 model-view-controller activerecord ruby-on-rails associations models

我是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"> 
Run Code Online (Sandbox Code Playgroud)

当我尝试创建一个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> 
Run Code Online (Sandbox Code Playgroud)

models/user.rb>

class User < ApplicationRecord
  has_many :posts
end
Run Code Online (Sandbox Code Playgroud)

models/post.rb>

class Post < ApplicationRecord
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

dp7*_*dp7 5

Rails 5中,在创建帖子时设置了状态验证.user_idposts belongs_to user

您可以从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
Run Code Online (Sandbox Code Playgroud)

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

class Post < ApplicationRecord
  belongs_to :user, optional: true
end
Run Code Online (Sandbox Code Playgroud)