Rails ActiveRecord不保存

时间:2017-03-27 16:54:20

标签: ruby-on-rails ruby activerecord

当我在rails console中调用它时,这将返回我想要的数据:

class VendorFinding < ActiveRecord::Base
    self.table_name = "vendor_findings"
    self.primary_key = "vendor_findings_id"

    def self.getReleventData()
        return VendorFinding
        .select([:ContactPerson, :contact_email])
        .where(Status: "Open")
    end
end    

但是当我尝试INSERT / UPDATE一行时,它假装一切顺利但是当我检查数据库时没有新的记录。
Rails控制台示例:

irb(main):004:0> myFinding = VendorFinding.new
=> #<VendorFinding vendor_findings_id: nil, ContactPerson: nil, contact_email: nil, Status: nil>

irb(main):007:0> myFinding.ContactPerson = "Myself"                                                                     
=> "Myself"
irb(main):008:0> myFinding
=> #<VendorFinding vendor_findings_id: nil, ContactPerson: "Myself", contact_email: nil, Status: nil>
irb(main):009:0> myFinding.save
   (1.9ms)  SAVEPOINT active_record_1
  SQL (1.9ms)  INSERT INTO `vendor_findings` (`ContactPerson`) VALUES ('Myself')
   (1.8ms)  RELEASE SAVEPOINT active_record_1
=> true    
irb(main):012:0> VendorFinding.where("ContactPerson = 'Myself'")                                                      
  VendorFinding Load (3.2ms)  SELECT `vendor_findings`.* FROM `vendor_findings` WHERE (ContactPerson = 'Myself')
=> #<ActiveRecord::Relation [#<VendorFinding vendor_findings_id: 905, ContactPerson: "Myself", contact_email: nil, Status: nil]>

它假装它更新了数据库,但是当我检查MySQL数据库时,记录不存在,并且记录计数总数与操作之前相同。数据库端没有验证,参数类型是VARCHAR(65),除了id,即INT。

我对rails很新,并且我试图让ActiveRecord与仍在使用的旧数据库进行交互,因此我无法修改列名以适应rails约定。为了让这个工作,我还需要做些什么吗?或许这根本不是问题。

提前感谢您的时间。

使用database.yml文件更新:

 development:
   adapter: mysql2
   host: <dbname>.db.<corpname>.com
   port: 8200
   database: Safety
   encoding: utf8
   collation: utf8_general_ci
   pool: 5
   <password_stuff_removed_for_stack_overflow>

   adapter: sqlite3
   database: ":memory:"

 beta:
   adapter: mysql2
   host: <dbname>.db.<corpname>.com
   port: 8200
   database: Safety
   encoding: utf8
   collation: utf8_general_ci
   pool: 5
   <password_stuff_removed_for_stack_overflow>

 production:
   adapter: mysql2
   host: <dbname>.db.<corpname>.com
   port: 8200
   database: Safety
   encoding: utf8
   collation: utf8_general_ci
   pool: 5
   <password_stuff_removed_for_stack_overflow>

 test:
   adapter: sqlite3
   database: db/test.sqlite3

1 个答案:

答案 0 :(得分:2)

你的问题出在database.yml的这一部分:

 development:
   adapter: mysql2
   host: <dbname>.db.<corpname>.com
   port: 8200
   database: Safety
   encoding: utf8
   collation: utf8_general_ci
   pool: 5
   <password_stuff_removed_for_stack_overflow>

   adapter: sqlite3
   database: ":memory:"

此代码的第一部分将您的开发数据库设置为与您的生产数据库相同。然后代码的第二部分将覆盖您之前的设置,并将数据库设置为database: ":memory:",这基本上是一个临时数据库,一旦连接关闭就会被删除。

你可以这样解决它:

 development:
   adapter: sqlite3
   database: "db/development.sqlite"

这将使用sqlite创建一个空的开发数据库。您将能够通过访问sqlite数据库来查看这些更改。但是,除非您在生产模式下运行代码,否则您将在生产mysql数据库中查看它们。