Rails 简单模型属性未保存到数据库

Rails simple model attributes not saved to database

我正在开发一个小型 Rails 3 应用程序,它可以从 Steam API 读取数据。我看到的是我创建的任何 ActiveRecord 模型的模型属性都没有保存到数据库中,如果我 debug 它们也不会输出。

这是我的示例模型

class NonPlayableApp < ActiveRecord::Base
  attr_accessor :name, :steam_id
  attr_accessible :name, :steam_id
end

迁移文件为:

class CreateNonPlayableApps < ActiveRecord::Migration
  def change
    create_table :non_playable_apps do |t|
      t.string :name
      t.string :steam_id
      t.timestamps
    end
  end
end

这里有一些使用 Rails 控制台的测试,当我在控制器和 inspectyaml 模型中尝试它们时,我得到了相同的结果:

irb(main):001:0> temp = NonPlayableApp.new( steam_id: 33333, name: "Testing" )
=> #<NonPlayableApp id: nil, name: nil, steam_id: nil, created_at: nil, updated_at: nil>
irb(main):002:0> temp.steam_id
=> 33333
irb(main):003:0> temp.name
=> "Testing"
irb(main):004:0> temp.save
   (0.1ms)  begin transaction
  SQL (4.0ms)  INSERT INTO "non_playable_apps" ("created_at", "name", "steam_id", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Fri, 26 Feb 2016 19:40:37 UTC +00:00], ["name", nil], ["steam_id", nil], ["updated_at", Fri, 26 Feb 2016 19:40:37 UTC +00:00]]
   (8.8ms)  commit transaction
=> true
irb(main):005:0> temp.steam_id
=> 33333
irb(main):006:0> temp
=> #<NonPlayableApp id: 64, name: nil, steam_id: nil, created_at: "2016-02-26 19:40:37", updated_at: "2016-02-26 19:40:37">
irb(main):007:0> temp2 = NonPlayableApp.first
  NonPlayableApp Load (1.6ms)  SELECT "non_playable_apps".* FROM "non_playable_apps" LIMIT 1
=> #<NonPlayableApp id: 64, name: nil, steam_id: nil, created_at: "2016-02-26 19:40:37", updated_at: "2016-02-26 19:40:37">
irb(main):008:0> temp2.steam_id
=> nil
irb(main):009:0> temp2.name
=> nil

我错过了什么?

attr_accessor :name, :steam_id 覆盖 setter 和 getter 方法 Rails 自动为该属性生成。

只需从您的模型中删除 attr_accessor :name, :steam_id 行。