【问题标题】:Model attributes are magically being set模型属性被神奇地设置
【发布时间】:2016-08-14 00:04:25
【问题描述】:

我的代码可以让我自动创建记录或更新记录的属性(如果它已经存在)。

代码如下所示:

class User < ApplicationRecord
  def self.update_or_create(attributes)
    user = first || new
    user.assign_attributes(attributes)
    user.save
    user
  end
end

当我调用它时,我可以这样做:

User.where(provider: auth.provider, uid: auth.uid).update_or_create(display_name: hash.display_name)

执行该代码将找到具有匹配 provideruid 的记录并将其更新为 display_name 或创建一个包含所有前面提到的所有 4 个属性集的全新记录。

这是如何工作的?

具体来说,我似乎无法理解对 user.save 的调用如何能够“获取”provideruid 的属性,因为它们仅在搜索上下文中提供,而不是作为属性传递到update_or_create

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-activerecord


    【解决方案1】:

    User.where(provider: auth.provider, uid: auth

    你上面有一个 User::ActiveRecord_Relation 这是一个类用户的集合

    def self.update_or_create

    self.update_or_create 这个方法是用户的类方法

    user = first || new

    现在你有一个集合的第一个实例或初始化一个用户类的新实例

    user.assign_attributes(attributes)

    在这里您为新实例或集合的第一个实例分配属性

    def self.update_or_create(attributes)
      puts "here I have a = #{self.class.name}" #user class
      user = first || new
      puts "here I have a = #{user.class.name}" #instance
      user.assign_attributes(attributes)
      user.save
      user
    end
    

    #编辑

    为了您完全理解,请在您的GemFile 中安装gem 'pry'

    此 gem 将能够在运行时调试您的代码

    def self.update_or_create(attributes)
      binding.pry ## add this your code and run this method in your app or rails console
      # at this moment when you execute the code the pry will provide a prompt
      # and type a self and press enter
      # and type a user and press enter
      # and type a next and press enter
      # you will see step by step want is happens 
      user = first || new
      user.assign_attributes(attributes)
      user.save
      user
    end
    

    更多信息请关注RailsCast Pry With Rails

    【讨论】:

    • 感谢您的回答,但我不明白。我听不懂你的回答,我也不明白传递给where 的参数是如何进入实例的
    • 如果需要更多帮助来理解这一点,请告诉我
    猜你喜欢
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多