[英]How do I save to database from a model Method in rails
我的用戶 model 中有一個名為unique_identifier
的字段,我想用下面的create_unqiue_identifier
方法的結果填充該字段。
如何為用戶將其添加到數據庫中?
class User < ApplicationRecord
has_secure_password
def create_unique_identifer
loop do
self. unique_identifier = SecureRandom.hex(5) # or whatever you chose like UUID tools
break unless self.class.exists?(:unique_identifier => unique_identifier)
end
// add something here to store unique_identifer to the database?
end
end
我已經想通了,我必須將create_unique_identifier
的結果返回給我的 controller。 然后在 controller 中,我可以為用戶保存unique_identifier
。
def create_unique_identifer()
loop do
self. unique_identifier = SecureRandom.hex(5) # or whatever you chose like UUID tools
break unless self.class.exists?(:unique_identifier => unique_identifier)
end
unique_identifier
end
為了保存,我將以下代碼添加到我的 controller 中:
if @user.unique_identifier.nil?
unique_identifier = @user.create_unique_identifer
@user.update(unique_identifier: unique_identifier)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.