Get ID of Rails Model before saving…?

后端 未结 10 1223
鱼传尺愫
鱼传尺愫 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:29

    I just ran into a similar situation when creating a data importer. I was creating a bunch of records of different types and associating them before saving. When saving, some of the records threw validation errors because they had validate_presence_of a record that was not yet saved.

    If you are using postgres, active record increments the id it assigns to a Model by keeping a sequence named models_id_seq (sales_id_seq for Sale etc.) in the database. You can get the next id in this sequence and increment it with the following function.

    def next_model_id
        ActiveRecord::Base.connection.execute("SELECT NEXTVAL('models_id_seq')").first["nextval"].to_i
    end
    

    However, this solution is not good practice as there is no guarantee that active record will keep id sequences in this way in the future. I would only use this if it was used only once in my project, saved me a lot of work and was well documented in terms of why it should not be used frequently.

提交回复
热议问题