简体   繁体   English

Rails-成功调用ActiveRecord.save后,id仍为0

[英]Rails - after call ActiveRecord.save successfully, the id still = 0

I have an entity which is an ActiveRecord. 我有一个ActiveRecord实体。 When I call entity.save it returns true , and the entity.new_record? 当我调用entity.save它返回true ,而entity.new_record? returns false , but the entity.id is 0. In the entities table, the new row was still inserted with the correct incremented id. 返回false ,但是entity.id为0。在实体表中,新行仍以正确的递增id插入。 It's very weird. 很奇怪

My rails version was 3.2.8, database is Mysql, and use gem mysql2 (0.3.11). 我的rails版本是3.2.8,数据库是Mysql,并使用gem mysql2(0.3.11)。 I've struggled with this for a whole day... 我整整为此苦了一天...

Code added: json is a string from frontend. 添加的代码:json是来自前端的字符串。

        o = JSON.parse(CGI.unescape(json))
        if o.has_key?('cls') then
            @r = o['cls']
            cls = o['cls']
            #create
            if o['action'] == 0 then
                entity = Object.const_get(cls).new
                o.each_pair do |k,v|
                    # entity.respond_to?  check method exist
                    if defined? entity[k] then
                        entity[k] = v
                    end
                end

                r = entity.save!

and the model (generated by rails g model): 和模型(由rails g模型生成):

class Node < ActiveRecord::Base
  attr_accessible :iNodeId, :level, :name, :pNodeId, :stationId, :type
end                    

Works by changing 通过改变来工作

if defined? entity[k] then 

to this 对此

if defined? entity[k] and k != 'id' then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM