Rails3 ActiveRecord: nil id on auto_increment field following create /save
Rails 3.0.9 Ruby 1.9.2p180 mysql 5.5
I'm creating entries in a mysql table, where the primary key = id with auto_increment. Record creation is done via calls to
mc_object = ModelClass.create( ... pram list excl id )
The returned mc_object contains an id = nil, while the DB record contains a correctly assigned id value. Using ModelClass.new(...) followed by ModelClass.save (or even save!) yi开发者_运维问答elds the same result.
I do not believe this is the correct behaviour.
If I re-query the record from the DB, I see the correct id in the returned object.
Is this a bug in ActiveRecord??
Id is created at time of saving the object into DB. If you use ModelClass.new(...) you will always get id = nil, but if you use ModelClass.create(...) you must get the value of id. Following example have a card object whose card_id field is auto inc.
irb(main):020:0> c = Card.create(:name =>"Sample Card")
=> #<Card name: "Sample Card", card_id: 65 >
irb(main):021:0> c = Card.new(:name =>"Sample Card")
=> #<Card name: "Sample Card", card_id: nil >
精彩评论