开发者

How to show an auto-incremental ID on a "create new record" form with Rails

I'm trying to create a form that will show the id that the record is going to have, prior to hitting submit on the form. For example, if I have a form to create a new project, and the previous project was id 3, I want the new project form to autopopulate with 4, so that I know that it's going to be 4 before I submit the form.

开发者_开发知识库Thanks for any help you can provide!

--Mark


Not entirely sure why you want to do this, but there are different methods depending on the database technology being used. However, you don't want to use these methods as your application would no longer be database agnostic.

A crude and simple approach would be to select the last row in your table and simply increment it's id.

Example:

next_id = Project.last.id + 1

However, I do not endorse this solution whatsoever, especially because there's no guarantee that next_id will be available by the time you click save if there are multiple users logged in and creating projects at the same time.

What I would recommend instead is using a different column that can be used as secondary unique identifier, perhaps something like a GUID. Whatever it may be, use something that can generated and will unique to that instance.


You can't really do this if you are using an auto_increment without actually creating the record in the database first. You might therefore need to use a different strategy to generate the id for the record.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜