Get ID of Rails Model before saving…?

后端 未结 10 1235
鱼传尺愫
鱼传尺愫 2020-12-16 13:03

How do you get the id of a rails model before it is saved?

For example, if I create a new model instance, how can I get its ID before it is saved?

I know t

10条回答
  •  暖寄归人
    2020-12-16 13:21

    First understand the structure of database.

    • Id is gerated using sequence.
    • increament done by 1 (specified while creating sequence)
    • Last entry to database will have highest value of id

    If you wanted to get id of record which is going to be saved,

    Then you can use following:

     1. id = Model.last.id + 1
        model = Model.new(id: id)
        model.save
        # But if data can be delete from that dataabse this will not work correctly.
    
     2. id = Model.connection.select_value("Select nextval('models_id_seq')")
        model = Model.new(id: id)
        model.save
        # Here in this case if you did not specified 'id' while creating new object, record will saved with next id. 
    
        e.g. 
        id
        => 2234
        model = Model.new(id: id) 
        model.save 
        # Record will be created using 'id' as 2234  
    
        model = Model.new()
        model.save
        # Record will be created using next value of 'id' as 2235  
    

    Hope this will help you.

提交回复
热议问题