2017-08-14 75 views
0

我需要自動填充基於MyModel.id的字段。什麼是正確的before_x類似過濾器使用?我使用的私有方法是這樣的:Rails - 在創建時自動填充基於id的字段

def _generate_code 
    hashids = Hashids.new("this is my salt", 6) 
    self.code = 'WA' + hashids.encode(self.id).upcase 
end 

我也需要保護validates_presence_of :codevalidates_uniqueness_of :code

的問題是,在before_save的Model.id是不存在的,我不能達到after_save因爲失敗驗證

+0

CHEC k this:https://stackoverflow.com/a/22684610/3609100 –

+0

我在我的_generate_code方法中放了'next_id = Wallet.connection.select_value(「Selectvalval('wallets_id_seq')」)',但它保持失敗驗證 – davideghz

+0

代碼uniq失敗?你是否記得在_generate_code中使用'next_id'而不是self.id(在調用它時它可能總是爲null)? –

回答

0

下面的代碼在before_validation過濾器被調用時工作

def _generate_code 
    if !self.code 
    next_id=Wallet.connection.select_value("Select nextval('wallets_id_seq')") 
    hashids = Hashids.new("this is my salt", 6) 
    self.code = 'WA' + hashids.encode(next_id).upcase 
    end 
end