Rails 模型字段未更新到数据库 [英] Rails model fields not updating to database
问题描述
class Car < ActiveRecord::Base
attr_accessor :model,:edition
attr_accessible :model,:edition
has_many :wheels
end
class Wheel < ActiveRecord::Base
attr_accessor :type,:tubeless
attr_accessible :type,:tubeless
belongs_to :car
end
创建操作
irb(main):009:0> bnz = Car.create :model=>"BENZ" , :edition=>2011
=> #<Car id: 5, model: nil, edition: nil, created_at: "2011-08-26 09:08:08", upd
ated_at: "2011-08-26 09:08:08">
问题:以上创建记录成功,但我的 :model 和 :edition 值没有发送到数据库.只有 id、created_at、updated_at 值在数据库中创建.
Problem: The above creates record successfully but my :model and :edition values are not sent to database. only id,created_at,updated_at values are getting created in database.
irb(main):010:0> fifth = Car.find(5)
irb(main):011:0> fifth.update_attributes(:edition=>2011, :model=>"BENZ")
=> true
irb(main):012:0> fifth.update_attributes!(:edition=>2011, :model=>"BENZ")
=> true
irb(main):013:0> fifth.update_attributes!(:edition=>2012, :model=>"BENZ")
=> true
irb(main):014:0>
问题:这里什么也没有发生.在 development.log 中只触发 select 语句,不触发 update 语句
Problem: Nothing is happening here. In developement.log only select statements are fired, no update statement is fired
我正在使用 sqlite 数据库.使用 sqlite manager firefox addon 查看数据库表.Rails 新手,感谢您的帮助.
I'm using sqlite db. Using sqlite manager firefox addon to view the db tables. New to rails, Thanks for help.
推荐答案
您不应该使用 attr_accessor
,因为它定义了虚拟属性,覆盖了用于字段的 setter.从模型中删除使用它的那些行,应该没问题.
You should not use attr_accessor
as that is defining virtual attributes, overriding the setters uses for the fields. Remove those lines using it from your models and it should be fine.
这篇关于Rails 模型字段未更新到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!