Just for experiement purpose, I typed following commends into rails console. I queried an arbitrary item and assign it a category_id and call "save". Why, in the result, nothing has changed (category_id of the item is still null)?
(some output has be omitted for clarity)
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>
Also tried 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>
------------------------------------------------Edit ----------------------------
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
Try with another attribute "price", it works. That is to say, rails prevent manually changes to attributes end with "_id", presumably to protect foreign key?
can anyone confirm this? or reproduce this?
------------------------------------Edit again --------------------------------- Model attached
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
Didn't see your last update. Yes, if you use
attr_accessor :user_id, :category_id
You can't change this values in console, as you tried to do it
attr_accessor is a ruby method that makes a getter and a setter, attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or up update_attributes(attrs).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.