Rails如何获取插入行的id(不是最后一个插入的)

3
在我的模型中,我有类似于以下代码的内容:
Report = Report.new()
Report.Name = name
Report.save()

这个过程会并行地在几秒钟内发生多次。如果我获取最后插入的id,它会给我错误的结果。我不想要数据库中最后插入行的id,我需要实际插入行的id。我该怎么做?


2
你真的确定要这样做吗:Report = Report.new()?你正在用它的一个实例替换Report类,可能这不是你想要做的。 - toro2k
report = report.newreport = report.new() 有区别吗?我不明白你的意思(抱歉,我还在学习 Rails)。 - Kush
重点不在于括号;当你写Report = Report.new时,你正在用该类的一个实例替换变量Report,这肯定是错误的。 - toro2k
2
你想要在赋值的左边使用小写的 report - johnsyweb
@Johnsyweb 谢谢!这解释了我之前遇到的错误。 - Kush
2个回答

12
report = Report.new
report.name = name
report.save
p report.id # here you get the id

谢谢亲爱的。 :) - Chinmay235

1

所需的函数是mysql_insert_id()

更多详细信息请参见-: mysql文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接