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 :code
和validates_uniqueness_of :code
的問題是,在before_save
的Model.id是不存在的,我不能達到after_save
因爲失敗驗證
CHEC k this:https://stackoverflow.com/a/22684610/3609100 –
我在我的_generate_code方法中放了'next_id = Wallet.connection.select_value(「Selectvalval('wallets_id_seq')」)',但它保持失敗驗證 – davideghz
代碼uniq失敗?你是否記得在_generate_code中使用'next_id'而不是self.id(在調用它時它可能總是爲null)? –