Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ID of Rails Model before saving...?

How do you get the id of a rails model before it is saved?

For example, if I create a new model instance, how can I get its ID before it is saved?

I know that the id is created onsave and according to the database but is there a workaround?

like image 545
amaseuk Avatar asked Aug 12 '10 11:08

amaseuk


2 Answers

I was looking for this too, and I found an answer:

Let's suppose model name is "Model" and table name is "models"

model.rb

before_save {
    next_id=Model.connection.select_value("Select nextval('models_id_seq')")
}

This will output the value your record will take for id IF it gets saved

like image 158
Ruby Racer Avatar answered Oct 10 '22 12:10

Ruby Racer


Usually when people think they need to do this they actually do not need to do it. Like John says, explain what you are trying to do and someone can probably suggest a way to do it without having to know the id in advance.

like image 32
Max Williams Avatar answered Oct 10 '22 11:10

Max Williams