Get ID of Rails Model before saving…?

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

    I was looking for this too, and I found an answer:

    Let's suppose model name is "Model" and table name is "models"

    model.rb

    before_save {
        next_id=Model.connection.select_value("Select nextval('models_id_seq')")
    }
    

    This will output the value your record will take for id IF it gets saved

    0 讨论(0)
  • 2020-12-16 13:35

    I don't believe there are any workarounds since the id is actually generated by the database itself. The id should not be available until after the object has been saved to the database.

    0 讨论(0)
  • 2020-12-16 13:38

    Consider doing what you want right after the instance is created.

    after_create do
      print self.id
    end
    
    0 讨论(0)
  • 2020-12-16 13:38

    I know it's an old question, but might as well throw my answer in case anyone needs to reference it

    UserModel

    class User < ActiveRecord::Base
    before_create :set_default_value
    
    def set_default_value
       self.value ||= "#{User.last.id+1}"
    end
    
    0 讨论(0)
提交回复
热议问题