仅出于实验目的,我在 Rails 控制台中输入了以下建议。我查询了一个任意项目并为其分配了一个 category_id 并调用“保存”。为什么结果没有任何变化(项目的category_id 仍然为空)?
(为清楚起见,省略了一些输出)
1.9.3-p327 :004 > i = Item.first
Item Load (0.2ms) SELECT "items".* FROM "items" LIMIT 1
1.9.3-p327 :005 > i.category_id =1
1.9.3-p327 :006 > i.save
(0.1ms) begin transaction
(0.1ms) commit transaction
=> true
1.9.3-p327 :007 > i
=> #<Item id: 1, title: "near", price: 1000.0, photos: nil, created_at: "2013-07-31 15:19:24", updated_at: "2013-07-31 15:51:46", user_id: nil, category_id: nil, location_id: 1>
还尝试了 update_attributes
1.9.3-p327 :008 > i.update_attributes(:category_id => 1)
(0.1ms) begin transaction
(0.1ms) commit transaction
=> true
1.9.3-p327 :009 > i
=> #<Item id: 1, title: "near", price: 1000.0, photos: nil, created_at: "2013-07-31 15:19:24", updated_at: "2013-07-31 15:51:46", user_id: nil, category_id: nil, location_id: 1>
- - - - - - - - - - - - - - - - - - - - - - - - 编辑 - --------------------------
1.9.3-p327 :007 > i.price=50
=> 50
1.9.3-p327 :008 > i.save
(0.1ms) begin transaction
(0.3ms) UPDATE "items" SET "price" = 50.0, "updated_at" = '2013-07-31 21:28:33.643283' WHERE "items"."id" = 1
(229.6ms) commit transaction
=> true
尝试使用另一个属性“价格”,它可以工作。也就是说rails防止手动修改以“_id”结尾的属性,大概是为了保护外键吧?
谁能证实这一点?或重现这个?
------------------------------------再次编辑------------ --------------------- 附模型
class Item < ActiveRecord::Base
attr_accessible :photos, :price, :title, :user_id, :category_id
attr_accessor :user_id, :category_id
belongs_to :user
belongs_to :category
belongs_to :location
end