views:

89

answers:

3

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?

+1  A: 

Using the default Rails convention of an auto-incrementing integer primary key, there's no way to get the ID of a model before it's saved because it's generated by the RDBMS when the new row is inserted in the relevant table.

What problem are you actually trying to solve?

John Topley
Hi, I want to create a new DDFORM model that is related (one-to-one) to another model MEMBERSHIP. Membership is created during a multi-step form and I would like to create (and provide a link to the DDFORM ) during the membership creation process.Perhaps the best way is to save membership and then end the multi-step form and begin a separate one thereafter...
aaronmase
I think you should post that as a separate question on here.
John Topley
A: 

I don't believe there are any workarounds since the id is actually generated by the database itself. The id should not be available until after the object has been saved to the database.

Curtis Edmond
+1  A: 

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.

Max Williams
True, it's a tricky process I am trying to develop. I should rethink the design...!
aaronmase