Search code examples
ruby-on-railsactiverecordmodel-view-controllerassociationsmodels

can't create object in rails console - model associations


I'm new to RoR and I'm practicing Models and Associations.

I've created two Models with belongs_to association. When I try to create an Object of one of the Models via Rails Console, I get a rollback transaction and I don't know why. All help will be appreciated!

I've created the User successfully:

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

When I try to create a Post object, I get this:

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

Solution

  • In Rails 5, presence validation is set for user_id while creating posts as posts belongs_to user.

    You can disable this behavior from 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
    

    You can disable this behavior using optional: true option in your association as well:

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