开发者

how to get next ID in a table in Rails

开发者 https://www.devze.com 2022-12-19 13:18 出处:网络
I have a table that has following columns idstore_idstore_name id and store_id are always going to be same. Since I am new to rails...I had created it by mistake.But I can\'t afford to go back and

I have a table that has following columns

id   store_id   store_name  

id and store_id are always going to be same. Since I am new to rails...I had created it by mistake. But I can't afford to go back and change stuff now since I am using store_id at a lot of places.

Issue 1: I am making admin screen for this table. When I try to insert a record, eventhough, id gets inserted (rails automatically gets the next one) NULL is being inserted in store_id.

Is there any ways I can have same number in store_id as in id while inserting record using the create method. Is there something that can be put in the model so that it is always execute before creating a record. and there I can have access to the next Id that should be inserted?

Issue 2: Since I am making admin screens for this table now..before I was just inserting data into this table by hand. I have inserted 5 records by hand so id and store_id 1..5 already exist. Now when I try to insert a record from admin screen it says duplicate key violates constraint. could开发者_运维问答 it be trying to insert id of 1 since this is the first time I am inserting record to this table using rails?


Issue 1: Until you can remove the store_id column, override the getter in the model for compatibility.

def store_id
  id
end

As for Issue 2: make sure your create code is not manually setting the id. The next record should be inserted with id 6, as long as your object has no id defined. Try it from script/console.


I think you should just change your code to only use the ID. A competent editor will be able to tell you where you have used store id in your project, and your tests will help if you introduce a regression error.

Otherwise, you could use a database trigger. Or setup a callback on the model to set store_id from the newly created id value (look at the after_create callback). Again, both of these approaches are hacks to cover up a bug in your system with an easy fix.


You can set custom primary key for ActiveRecord models:

class Store < ActiveRecord::Base
  set_primary_key :store_id
end

Then you can create a new migration that removes 'id' column and updates 'store_id' column to be a primary key.

0

精彩评论

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

关注公众号