ruby-on-rails - Ruby on Rails 从哈希递归地实例化活动记录模型
问题描述
我有两个继承自的类ActiveRecord::Base
,一个User
可能有很多Badge
s。
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)
有什么方法可以从这个哈希中递归地实例化我的所有模型,还是我需要在我的User
类initialize
方法中手动执行?
我想出解决这个问题的是:
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.
解决方案
ActiveRecord 不支持多次初始化,这意味着您不能传递一个数组并期望有一个类的多个实例,因为这就是它们所反映的,new
用于实例化一个属于 X 类的新对象,该对象继承自ActiveRecord::Base
.
您可以做的是使用create
,它可以接受包含您要创建的每条记录的数据的哈希数组。
推荐阅读
- javascript - Javascript 代理:防止在多级对象上不存在属性时调用任何其他属性
- android - 新的 gradle 版本在 App 级别 build.gradle 中没有依赖项部分
- r - 有条件地设置 RowGroup 样式
- javascript - 如果我设置 dev-server 的 contentBase 路径,webpack 不会提供更新的文件
- python-docx - 我对 Python 编程非常陌生,并且对 python-docx 有疑问:paragraph.py 中的函数 add_r() 在哪里定义?
- javascript - 模拟导出为对象的 ES6 类模块
- core-data - 添加具有重复项的唯一约束的核心数据崩溃
- ffmpeg - 简单的 hls 服务器 - 从本地 NAS 流式传输
- algorithm - 到达目的地的最短天数 | 图形
- flutter - 面对 sliver appbar 的 RenderFlex 溢出问题