首页 > 解决方案 > Ruby on Rails 从哈希递归地实例化活动记录模型

问题描述

我有两个继承自的类ActiveRecord::Base,一个User可能有很多Badges。

class User < ActiveRecord::Base
  has_and_belongs_to :badges
  has_one :user_info
  accepts_nested_attributes_for :user_info
end
class Badge < ActiveRecord::Base
  has_and_belongs_to :users
end

当我为 a 进行 API 调用时,User我得到以下响应:

{
    "UserInfo": {
        "CursePeriod": null,
        "IsCursed": false,
        "IsBanned": false,
    },
    "Badges": [
        {
            "Name": "kayıp",
            "Description": "kim bilir nerede"
        },
        {
            "Name": "çaylak",
            "Description": ""
        }
    ],
    "HasEntryUsedOnSeyler": false,
    "FollowerCount": 0,
    "FollowingsCount": 0,
    "Picture": null
}

当我将该json作为哈希传递给User.new我时

ActiveRecord::AssociationTypeMismatch: Badge(#47159034390540) expected,
got {:name=>"kayıp", :description=>"kim bilir nerede"} which is an instance of Hash(#47159016253160)

有什么方法可以从这个哈希中递归地实例化我的所有模型,还是我需要在我的Userinitialize方法中手动执行?

我想出解决这个问题的是:

class User < ActiveRecord::Base
  has_and_belongs_to_many :badges

  def initialize(attributes = {})
    create_badges(attributes.delete(:badges))
    super
  end

  def create_badges(badges = [])
    @badges = []
    badges.each do |badge|
      @badges << Badge.new(badge)
    end
  end
end

我只是问是否ActiveRecord已经支持我想要实现的目标,如果支持,如何实现?


更新

至于我的UserIdentifier课,即使我已经包括在内accepts_nested_attributes_for :user_info,我仍然得到

ActiveRecord::AssociationTypeMismatch: UserInfo(#46945688683560) expected,
got {:curse_period=>nil, :is_cursed=>false, :is_banned=>false} which is an instance of Hash(#46945670719200)

我如何得到该错误如下

# The hash that I pass to my User class

hash = {:user_info=>{:curse_period=>nil,
                     :is_cursed=>false,
                     :is_banned=>false},
        :badges=>[{:name=>"kayıp", :description=>"kim bilir nerede"},
                  {:name=>"çaylak", :description=>""}],
        :has_entry_used_on_seyler=>false,
        :follower_count=>0,
        :followings_count=>0,
        :picture=>nil}

# Then simply

User.new(hash)

# After the line above, I get the error I mentioned in my update.

标签: ruby-on-railsrubyactiverecord

解决方案


ActiveRecord 不支持多次初始化,这意味着您不能传递一个数组并期望有一个类的多个实例,因为这就是它们所反映的,new用于实例化一个属于 X 类的新对象,该对象继承自ActiveRecord::Base.

您可以做的是使用create,它可以接受包含您要创建的每条记录的数据的哈希数组。


推荐阅读