【发布时间】:2018-01-18 23:20:40
【问题描述】:
我正在尝试使用 ActiveRecord 进行“不简单”的查询:
ChatRoom.first.as_json(include: {
chat_room_members: {
include:{
user: {
include: [
hero_page: {
only: [:torch_id]
},
card: {
only: [:crop_y]
}
]
}
}}})
在模型中,一个ChatRoom 有很多ChatRoomMembers,其中有一个User,有一个HeroPage 和一个Card。
问题是 ActiveRecord 完全忽略了参数card。更具体地说,忽略 user: include{} 内第一个参数之后的所有参数:
{
"id" =>22,
"chat_room_members" => [
{
"id" =>7,
"user" => {
"id" =>22,
"hero_page" => {
"torch_id" =>"superhero23"
},
}
}
]
}
但是如果我从hero_page 或card 中删除only 参数,ActiveRecord 会显示一切正常。示例:
[...]
include: [
hero_page: {
only: [:torch_id]
},
:card
]
[...]
另一个奇怪的事实是我可以在第二个参数中输入任何内容(尊重语法)并且不会导致错误。示例:
[...]
include: [
hero_page: {
only: [:torch_id]
},
this: {
only: [:doesnt, :cause, :error]
}
]
[...]
就像在第一个示例中一样,仅显示 hero_page 并忽略另一个甚至不存在的参数 this。
有人知道为什么在这些情况下会忽略第二个参数吗?
【问题讨论】:
标签: ruby-on-rails json activerecord ruby-on-rails-5