Rails ActiveRecord#create won't save to database

时间:2015-06-25 19:04:15

标签: ruby-on-rails postgresql ruby-on-rails-4

I'm having issues getting ActiveRecord to save to my postgres database. When I run the #create command on my class in pry (console debugger), I get a the newly created class instance back and it's auto-incrementing the ID. However, it's not in the database. No errors are thrown in the postgres logs, despite tweaking all postgres log settings to be as verbose as possible. If #create fails validation I will see an error in the postgres logs. However, a successful #create statement simply isn't saving to the database. I am on a Mac and installed postgres via brew. Any ideas of what might be going on? This is driving me nuts and I've been at it all morning. Update #1: I'm not using database_cleaner or anything similar. Update #2: My pry console isn't showing any SQL, pass or fail. Here's what it looks like: [26] pry(#<RSpec::ExampleGroups::Tweet>)> Tweet.create({tweet_id: rand(111111111111111111..999999999999999999), author: 'adfsadfs', tweet: 'adfadfs', retweet_count: 3, latitude: 87.684, longitude: 41.364, tweet_created_at: Time.now}) => #<Tweet:0x007fb408f2f210 id: 64, tweet_id: 855873080844717219, author: "adfsadfs", tweet: "adfadfs", retweet_count: 3, latitude: #<BigDecimal:7fb408f2e2c0,'0.87684E2',18(45)>, longitude: #<BigDecimal:7fb408f2df78,'0.41364E2',18(45)>, created_at: Thu, 25 Jun 2015 14:08:33 CDT -05:00, updated_at: Thu, 25 Jun 2015 14:08:33 CDT -05:00, tweet_created_at: Thu, 25 Jun 2015 14:08:33 CDT -05:00> Update #3: I'm running pry in the middle of my rspec test. The entirety of my rspec file looks like this: require 'rails_helper' RSpec.describe Tweet, type: :model do it { binding.pry } pending end SOLVED: The issue is that I when the rspec test is cancelled prematurely or is marked pending, then the record isn't stored in the database.

1 个答案:

答案 0 :(得分:0)

在PostgreSQL中有transaction附带ACID保证的东西。一旦你进行交易,你几乎就是“在你自己的世界里”。您且只有您可以进行更改并看到它们已应用,其他任何观察者都不会看到这些更改。

如果其他人要查看您已应用的更改,则必须提交,否则所有更改都将丢失。如果应用程序决定发出ROLLBACK,如果发生故障(验证,异常,等等),则这些更改将丢失。如果连接断开,这些更改将丢失。如果进程终止,则会丢失这些更改。

测试套件通常在巨大的事务中运行。测试套件完成后,会发出ROLLBACK,数据库与测试运行前的数据库相同。这样,测试运行就不会在数据库的数据中留下任何痕迹:代码可能已经坏了和/或坏了,这可能会影响进一步的测试运行。对于的情况,测试套件在事务中运行。其缺点是:无法从外部观察到变化。

pry会话中,使用ActiveRecord的方法。由于它在正在进行交易的连接上运行,因此能够看到当时构建的状态。