开发者

updating wrong value to database

I'm just trying to increment a record by 1 starting at 2000, when a new record is created upon clicking on the create action to create a record:

if resource_model == Student then @resource.testing_id = id + 2000 end

So if the record has an id of 1, I assume that the testing_id will be 2001. But instead it returns: 2147483647 (maximum mysql limit?)

Any sug开发者_如何学编程gestions on how to address this? Thanks.


  1. You can't know record ID during create. ID is known after saving record do database.

  2. You can't relay on ID to give you values like 1, 2, 3 ... and so on.

  3. Don't store value like ID+2000, becouse you can get it at any time by calculating id+2000.

You can get next testing_id by something like this:

if resource_model == Student then
  @resource.testing_id = Student.first(:order => "testing_id DESC").testing_id + 1
end

But if two processes at the same time will fetch the same value then you will have duplicate testing_id.


Object.idf is a (deprecated) method that returns the Ruby object ID, which uniquely identifies the object. Rails has overridden id so that in models it refers to the database primary key. I'm going to take a guess that your code snippet is from a controller, and that's why id is returning a strange and large number: It's the Ruby object id of the controller, not the primary key of the object. Give id a receiver, e.g. @resource.id, and see how that works.


2147483647 = 2 ^(32-1) Could you show some of your code here?

From what i'm guessing here is that you are comparing apples with strawberries :P. I think you are adding a "1" on a string so that means for example:

2000 + 1 = 20001 20001 + 1 = 200001

So if you do that a couple of times this means you will get to the maximum size of an int (21475483647). I don't know this for a 100% sure, but this has to do with the way you ask your question and the way you don't post code etc... I hope this edit was helpfull tho.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜