Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby ActiveRecord Basics Migrations and Relationships Relationships

BJ Keeton
BJ Keeton
5,609 Points

Database gives "rollback transaction" on Rails Console .create method on Rails 5.

I keep getting this when I follow along

2.3.0 :008 > TimeEntry.create(time:1.2, customer_id: 2)
   (0.1ms)  begin transaction
  Customer Load (0.1ms)  SELECT  "customers".* FROM "customers" WHERE "customers"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
   (0.1ms)  rollback transaction
 => #<TimeEntry id: nil, time: 1.2, customer_id: 2, employee_id: nil, created_at: nil, updated_at: nil> 

I am using Ruby 2.3.0 and Rails 5. He said it shouldn't matter, but I realize that was talking about prior versions.

BJ Keeton
BJ Keeton
5,609 Points

The issue actually comes because It's Rails 5, actually.

Rails, in 5.0, requires validation on belongs_to. There are two ways to fix it, adding optional: true or required: false.

This code fixed my issue with committing to the DB, but I'm going to have to do some reading to see how this changes the way I've seen associations.

class TimeEntry < ApplicationRecord
    belongs_to :customer, required: false
    belongs_to :employee, required: false
end

If you're interested, http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html has a way to revert the behavior back to the functionality we were used to in Rails 4.x.

3 Answers

This worked for me. Thanks for posting this question, I really appreciate it!

Sherlynn Tan
Sherlynn Tan
39 Points

Thank you for the solution! This worked for me too.

Pedro Araya
Pedro Araya
1,912 Points

It worked for me also