catch22
catch22

Reputation: 1693

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

Upvotes: 1

Views: 3254

Answers (2)

dp7
dp7

Reputation: 6749

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

Upvotes: 9

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

you can easily check the reason behind the rollback, follow these steps, you can call errors method on post object. Do this

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

post.errors.full_messages will return an array containing rollback errors. Paste the errors you are getting here and we will help you out.

Hope that helps!

Upvotes: 4

Related Questions