【问题标题】:How to send HABTM as JSON in Rails API如何在 Rails API 中将 HABTM 作为 JSON 发送
【发布时间】:2016-02-15 16:56:50
【问题描述】:

我目前正在开发一个食谱应用程序,它在前端使用 Ember,在后端使用 Rails API。在 Rails 中,我在食谱和配料之间有很多关系。我的成分模型不仅存储成分名称,还存储营养信息,因此我无法将成分简单地存储为食谱上的数组字段。

我目前对如何设置 Rails API 以发送格式正确的 JSON 感到困惑。据此

website

Ember 期望 JSON 格式如下:

假设这是正确的,我应该如何在我的 Rails API 中实现这一点?

【问题讨论】:

    标签: ruby-on-rails json ember.js


    【解决方案1】:

    如果有人有类似的问题,我通过我的配方序列化程序解决了这个问题,类似于Stack Overflow Answer

    【讨论】:

      【解决方案2】:

      我使用 active_model_serializers (0.10.2) 和 Rails 5:

      class RecipeSerializer < ActiveModel::Serializer
        attributes :id, :name, :time, :yield, :servings, :url
      
        has_many :ingredients # not HABTM here!
      end
      

      http://localhost:3000/api/recipes/2这个:

      {
        "data": {
          "type": "recipes",
          "attributes": {
            "name": "test",
            "time" : "test2",
            "ingredients_ids": [1]
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多