【问题标题】:Append data from different model in json object在 json 对象中附加来自不同模型的数据
【发布时间】:2015-05-07 18:54:18
【问题描述】:

我正在尝试在我的 rails 应用程序中实现 Like 功能。 我现在要做的是我有模型问题、答案和点赞。

基本上, 问题模型具有问题详细信息,例如 user_id、question_text,答案模型具有答案详细信息,例如 user_id、answer_text 和 Like 模型 具有like 之间的关系user_id、question_id 和 answer_id。

在我的问题控制器中,我想呈现问题详细信息页面,它将向我们显示一个问题和几个答案。 我已经渲染了问题 json,以及与问题相关的答案。

{
  "questions": [
    {
      "id": 1,
      "text": "Turtoise",
      "user_id": 22
    }
  ],
  "answers": [
    {
      "id": 41,
      "question_id": 1,
      "user_id": 17,
      "text": "Good"
    },
    {
      "id": 7,
      "question_id": 1,
      "user_id": 17,
      "text": "alifff"
    }
  ],
  "isLike": [
    {
      "id": 1,
      "user_id": "17",
      "question_id": "1",
      "answer_id": null,
      "isLike": false
    }
  ]
}

现在我想像这样渲染 json

   {
  "questions": [
    {
      "id": 1,
      "text": "Turtoise",
      "isLike": {
        "id": 1,
        "user_id": "17",
        "question_id": "1",
        "answer_id": null,
        "isLike": true
      }
    }
  ],
  "answers": [
    {
      "id": 7,
      "text": "Good",
      "isLike": {
        "id": 2,
        "user_id": "17",
        "question_id": null,
        "answer_id": "8",
        "isLike": false
      }
    },
    {
      "id": 8,
      "text": "Nice",
      "isLike": {
        "id": 3,
        "user_id": "17",
        "question_id": null,
        "answer_id": "8",
        "isLike": false
      }
    }
  ]
}

你能给我一些想法如何做到这一点。

【问题讨论】:

  • 你的 json 格式不正确。请改正。
  • @Dato'MohammadNurdin 我已经更正了我的 json
  • 您可能需要覆盖模型中的 as_json 方法。在选项哈希中包含您想要包含的任何内容。然后你就可以走了。由于某些原因,我觉得您需要重新查看要呈现的 json。 api.rubyonrails.org/classes/ActiveModel/Serializers/…
  • 您使用的是哪个数据库?
  • 我正在使用 Postgresql .. @KaranPurohit

标签: ruby-on-rails json


【解决方案1】:

你可能需要在这里玩一下rails关系。

一般来说,您的Question hasMany Like, and Like belongsTo Question。答案也一样,Answer hasMany Like, and Like belongsTo Answer

由于Like可以belongsTo不止一个模型,你可以试试Polymorphism Association

http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

【讨论】:

  • 感谢您的回答。我会尽力去做,让你知道进度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多