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.
You can't know record ID during create. ID is known after saving record do database.
You can't relay on ID to give you values like 1, 2, 3 ... and so on.
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.id
f 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.
精彩评论