【问题标题】:How to get id values after saving an ActiveRecord model in rails在 Rails 中保存 ActiveRecord 模型后如何获取 id 值
【发布时间】:2011-06-13 09:31:08
【问题描述】:

我有一个名为 user 的 ActiveRecord 模型(我在 Rails 2.3.8 上),我将它保存为

user = User.new
user.name = "user name"
user.save!

我想做的是在创建用户后获取生成的用户ID。但目前它在保存时返回真/假值

如何获取保存的用户ID?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    保存后拨打user.id即可。

    【讨论】:

      【解决方案2】:

      对于在模型中寻找 on create 的人,方法如下:

      class User < ActiveRecord::Base  
      ...  
        after_create :do_something
      
        def self.do_something
         user_id = id #this will have last created id
         # use this according to your needs
        end
      ...
      end
      

      【讨论】:

        【解决方案3】:

        我的做法是

        class User < ActiveRecord::Base  
        ...  
          id = nil
          after_save {id = self.id}
        ...
        end
        

        然后局部变量id在整个模型中都是可用的

        【讨论】:

        • @Chowlett 把它钉在了上面。保存后只需引用user.id
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-18
        • 1970-01-01
        • 2017-12-28
        • 2017-02-02
        • 1970-01-01
        相关资源
        最近更新 更多