简体   繁体   English

如何从 Rails 中的 model 方法保存到数据库

[英]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.

相关问题 如何从Rails中的模型保存 - how do I save from a model in rails 如何将Nokogiri的抓取数据保存到Rails数据库? - How do I save the scraped data from Nokogiri to a Rails database? 如何在Rails的数据库中保存参数? - How do I save parameters in the database in rails? Rails:如何在我的模型中调用`self.save`并将其保留在数据库中? - Rails: How do I call `self.save` in my model and have it persist in the database? 如何返回通过Rails模型方法定义的属性数组以及数据库表中的属性? - How do I return an array of attributes defined via a Rails model method, as well as the attributes in the database table? 您如何使用Rails 3 gem方法来更新数据库模型? - How do you use a Rails 3 gem method to update a database model? Rails —如何从after_save回调中查看新旧模型的值? - Rails — How do I see old and new model values from an after_save callback? Rails:如何将来自模型中的 before_save 的错误添加到控制器中? - Rails: How do I add into the controller an error that comes from a before_save in the model? 在 Rails 中,如何从 JavaScript 查询我的数据库以便保存查询值? - In Rails, how do I query my database from JavaScript so I can save the value of the query? Rails:如何将字符串表示形式保存回模型中? - Rails: How do I save a string representation back into a model?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM