[英]How do I save to database from a model Method in rails
I have a field in my User model called unique_identifier
which I want to populate with the outcome of the create_unqiue_identifier
method below.我的用户 model 中有一个名为
unique_identifier
的字段,我想用下面的create_unqiue_identifier
方法的结果填充该字段。
How can I add this to the database for the user?如何为用户将其添加到数据库中?
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
I have figured this out, I have to return the result of create_unique_identifier
back to my controller.我已经想通了,我必须将
create_unique_identifier
的结果返回给我的 controller。 Then within the controller I can save the unique_identifier
for the User.然后在 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
to save I then added the below code to my controller:为了保存,我将以下代码添加到我的 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.