开发者

Error with save! method in Rails 3.1.0-rc6

Dont know what I am doing wrong.开发者_开发技巧.. Have this code:

new_model = Model.new(:brand_id=>brand_id, :name=>new_model_name)
new_model.save!
ModelImage.upload(new_model.id, params[:images])

but new_model.id equals to nil. WTF?

Tried in rails c, no errors. SQl is OK.

Thx.

Some code from Rails Console:

irb(main):045:0> h = Model.create(:brand_id=>2, :name=>'SKyFy')
SQL (0.1ms)  BEGIN
SQL (42.2ms)  INSERT INTO `models` (`brand_id`, `id`, `name`) VALUES (?, ?, ?)     [["brand_id", 2], ["id", nil], ["name", "SKyFy"]]
(118.7ms)  COMMIT
=> #<Model id: nil, brand_id: 2, name: "SKyFy">
irb(main):046:0> h.id
=> nil

Dont have any attr_*, validations. Models are clear.

Another example:

irb(main):048:0> h = Model.new(:brand_id=>1, :name=>'SKYDOS')
=> #<Model id: nil, brand_id: 1, name: "SKYDOS">
irb(main):049:0> h.save!
SQL (0.2ms)  BEGIN
SQL (3.4ms)  INSERT INTO `models` (`brand_id`, `id`, `name`) VALUES (?, ?, ?)  [["brand_id", 1], ["id", nil], ["name", "SKYDOS"]]
(83.5ms)  COMMIT
=> true
irb(main):050:0> h.id
=> nil
irb(main):051:0> h.errors
=> #<ActiveModel::Errors:0x9a37c18 @base=#<Model id: nil, brand_id: 1, name: "SKYDOS">,     @messages={}>
irb(main):052:0> 

PS Solved my problem... had TWO primary keys. Thx to all.


Set

config.active_record.schema_format = :sql

in config/application.rb

this should hopefully solve your problems.

Note the query,

INSERT INTO `models` (`brand_id`, `id`, `name`) VALUES (?, ?, ?)  [["brand_id", 1], ["id", nil], ["name", "SKYDOS"]

This query is wrong, Rails doesn't know about the primary key of the table and assumes (incorrectly) that id is just a normal column. With an SQL schema format - this should work fine.

You can confirm this by looking at db/schema.rb and you will end up with something like:

create_table "foos", :id => false, :force => true do |t|
  t.integer  "id",                                 :null => false
  ...
end


It's hard to say with so little information, but the answer most likely lies in your validations for new_model.

Have a look at new_model.rb and see if there are any validations that may be failing.

If not, see if you have an attr_accessible/attr_protected conflict.

To help you find the answer quickly, add the line:

logger.debug new_model.errors

after your save! and you'll see what's going on in your logs.


Make sure that you have primary key 'id' with auto_increment in model's table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜