Rails 简单模型属性未保存到数据库 [英] Rails simple model attributes not saved to database
问题描述
我正在开发一个从 Steam API 读取数据的小型 Rails 3 应用程序.我看到的是,我创建的任何 ActiveRecord 模型的模型属性都不会保存到数据库中,如果我 debug
它们,它们也不会输出.
I am developing a small Rails 3 app that reads data from the Steam API. What I am seeing is that the model attributes for any ActiveRecord model I create are not saved to the database nor are they output if I debug
them.
这是我的示例模型
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 控制台的测试,当我在控制器中尝试它们并inspect
或 yaml
模型时,我得到了相同的结果:
Here are few tests with the Rails console, I get the same results when I try them in a controller and inspect
or yaml
the model:
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
覆盖 Rails 自动为该属性生成的 setter 和 getter 方法.
attr_accessor :name, :steam_id
overrides the setter and getter methods that Rails automatically generates for that attributes.
只需从模型中删除 attr_accessor :name, :steam_id
行即可.
Just delete the attr_accessor :name, :steam_id
line from your model.
这篇关于Rails 简单模型属性未保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!