【问题标题】:get last insert id when using Activerecord使用 Activerecord 时获取最后一个插入 id
【发布时间】:2011-02-25 00:22:32
【问题描述】:

对于 Sqilte3 C API,我会使用 sqlite3_last_insert_rowid。插入新记录后使用 ActiveRecord 时如何获取此 ID?我使用以下方式插入新记录:

Section.new |s|
     s.a = 1
     s.b = 2
     #I expected the return value of save to be the last_insert_id, but it is NOT
     s.save   
end

【问题讨论】:

    标签: ruby sqlite activerecord


    【解决方案1】:

    'save' 方法根据保存是否成功返回 true 或 false 试试看:

    new_section = Section.new do |s|
        s.a = 1
        s.b = 2
        s.save   
    end
    
    p new_section 
    

    它应该打印您手动设置的所有字段以及任何自动填充的值,包括 last_insert_id 通常是记录“id”

    【讨论】:

      【解决方案2】:

      假设您已经使用 ActiveRecord 默认字段名称来保存主键,那么

      s.id
      将保存您刚刚保存的记录的 id。

      【讨论】:

        猜你喜欢
        • 2023-03-16
        • 2011-04-30
        • 2010-12-31
        • 2011-06-01
        • 1970-01-01
        • 2011-06-30
        • 2014-02-18
        • 1970-01-01
        相关资源
        最近更新 更多