Rails 3 - 如何从 mysql 表中查找最后插入的 ID
在我的控制器中,我有以下命令序列:
SAVE DATA INTO FIRST TABLE
_get ID of inserted item into table from first step_
SAVE DATA INTO SECOND TABLE WITH ID FROM FIRST COMMAND
if FIRST.save && SECOND.save
do something
我想知道如何获取立即插入数据库的项目ID...我尝试谷歌搜索,但找不到此信息...
提前致谢给你的提示
in my controller I have following sequence of commands:
SAVE DATA INTO FIRST TABLE
_get ID of inserted item into table from first step_
SAVE DATA INTO SECOND TABLE WITH ID FROM FIRST COMMAND
if FIRST.save && SECOND.save
do something
And I am wondering, how to get id of item, which is immediately inserted into database... I tried to googling, but I can't find this information...
Thanks in advance for your hints
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
保存模型后,您可以访问它的 id 变量:
After saving a model, you can access it's
id
variable:您可以通过模型中的
updated_at
字段搜索数据库吗?要获取最新记录:
或者更好的是,在首先保存 Model1 时:
分配:
注意:如果您确实想要保存特定记录的 ID,则查找最后一条记录并不可行最好的方法。
这是因为在插入 Model1 之后和调用 Model2 之前,其他用户可能会插入另一条记录。
如果您希望两者一起保存或根本不保存,您可以查看事务: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html
如果您对 Model1 在担心 Model2 之前自行保存感到满意,那么只需像我上面那样分配变量即可。
Could you just search your database by the
updated_at
field in your model?To get the most recent record:
or better yet, upon saving Model1 in the first place:
To assign:
Note: if you actually want to save the ID of a specific record, finding the last isn't the best way to go.
This is because another record could be inserted by a different user, right after you inserted Model1 and right before you call Model2.
If you want the two to save together or not at all, you can look into transactions: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html
If you're happy with Model1 saving on its own before worrying about Model2, then simply assign the variables as I did above.