我遇到了与includes
方法相关的嵌套rails模型的奇怪问题。我试图简单地将项目从一个对象移动到其父对象,如下所示:
当前
[
{
"created_on": "2014-09-11T15:52:34-04:00",
"id": 8,
"mail_notification": false,
"project_id": 2,
"user_id": 15,
"member_roles": [
{
"id": 10,
"inherited_from": null,
"member_id": 8,
"role_id": 3
}
]
}
]
需要:
[
{
"created_on": "2014-09-11T15:52:34-04:00",
"id": 8,
"mail_notification": false,
"project_id": 2,
"user_id": 15,
"role_id": 3
}
]
出于某种原因,当我遍历当前对象时,它会删除:member_roles
。一个很好的例子:
members = Member.includes(:member_roles).find_all_by_project_id(@project)
# Contains :member_roles
puts members.to_json(include: [:member_roles])
#=> [{"created_on":"2014-09-11T15:52:34-04:00","id":8,"mail_notification":false,"project_id":2,"user_id":15,"member_roles":[{"id":10,"inherited_from":null,"member_id":8,"role_id":3}]}]
# Does not contain :member_roles
puts members.first.attributes
#=> {"id"=>8, "user_id"=>15, "project_id"=>2, "created_on"=>Thu, 11 Sep 2014 15:52:34 EDT -04:00, "mail_notification"=>false}
为什么:member_roles
对象会消失?
答案 0 :(得分:0)
Member.includes(:member_roles)正急切地加载您的关系(即,当您第一次实际使用此对象时,它会获取成员集合所需的所有member_roles实例)
to_json(include:[:member_roles])包含父成员模型json中相关模型的json表示。
您所描述的内容称为方法委派(Module.delegate),但由于您的两个模型之间存在一对多关系,因此无法执行此操作