【问题标题】:Rails: as_json ignoring parameterRails:as_json 忽略参数
【发布时间】: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_pagecard 中删除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


    【解决方案1】:

    user.include 需要像您目前所做的那样是散列而不是数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-03
      • 2011-12-01
      • 2016-04-21
      • 2013-06-14
      • 2015-05-13
      • 2018-01-12
      • 2019-02-22
      • 2020-02-27
      相关资源
      最近更新 更多