代码之家  ›  专栏  ›  技术社区  ›  pierrotlefou

使用ActiveRecord时获取上次插入ID

  •  1
  • pierrotlefou  · 技术社区  · 14 年前

    对于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
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   zed_0xff    14 年前

    “save”方法根据保存是否成功返回true或false 试试史密斯:

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

    它应该打印您手动设置的所有字段以及任何自动填充的值,包括最后一个“插入”ID通常是记录“ID”

        2
  •  0
  •   stephenr    14 年前

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

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