【问题标题】:Ruby on Rails 5: How to print nested jsonRuby on Rails 5:如何打印嵌套的 json
【发布时间】:2016-12-05 18:47:31
【问题描述】:

我正在学习 Ruby on Rails(专门用于 API 开发),我需要一些帮助。 假设我们有 2 个表,“Brands”和“Cars”。
我要做的基本上是:

  1. 买车:我不想显示“brand_id: x”,而是显示“brand = { id: X, name: Y}”,就像嵌套的 JSON 一样。
  2. 为每辆车执行此操作。

现在,当我试图上车时,它给了我:

{
    "id": 1,
    "name": "Veneno",
    "brand_id": 1,
    "created_at": "2016-12-03T21:47:01.000Z",
    "updated_at": "2016-12-03T21:47:01.000Z"
  }

我的文件包含以下内容: 迁移文件:

class CreateBrands < ActiveRecord::Migration[5.0]
  def change
    create_table :brands do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreateItems < ActiveRecord::Migration[5.0]
  def change
    create_table :items do |t|
      t.string :name
      t.integer :brand_id

      t.timestamps
    end
    add_index :items, :brand_id
  end
end

型号:

class Brand < ApplicationRecord
  has_many :items
end

class Item < ApplicationRecord
  belongs_to :brand
end

目前,我的 items_controller.rb 是:

class ItemsController < ApplicationController
  before_action :set_item, only: [:show, :update, :destroy]

  # GET /items
  def index
    @items = Item.all
    render json: @items
  end

  # GET /items/1
  def show
    render json: @item, :only => [:id, :name]
  end

  # POST /items
  def create
    @item = Item.new(item_params)

    if @item.save
      render json: @item, status: :created, location: @item
    else
      render json: @item.errors, status: :unprocessable_entity
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_item
      @item = Item.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def item_params
      params.require(:item).permit(:name, :brand_id)
    end
end

谢谢!我 24/7 全天候在线提供有关此问题的更多信息。我用谷歌搜索了很多,但我找不到如何解决这个问题。

【问题讨论】:

    标签: ruby-on-rails json ruby api


    【解决方案1】:

    您所描述的是您希望如何序列化您的模型。有一些 gem 可以为这个问题提供强大的解决方案(例如,古老但仍然相关的 active_model_serializers),但对于基本用例,您可以利用 Rails 令人惊讶的强大 as_json

    例如,让你的 show 方法包含品牌对象:

    class ItemsController
      # GET /items/1
      def show
        render json: @item, :includes => [:brand]
      end
    end
    

    您还可以在模型级别覆盖默认的 as_json,但是当不同的调用者需要不同的序列化和详细级别时,该解决方案会变得很棘手。请参阅 Include associated model when rendering JSON in Rails 以获取与您所描述的类似但更多的示例。

    【讨论】:

    • 感谢您的快速回复!我刚刚尝试了该代码但无法正常工作,我得到了带有“brand_id”属性的项目。尝试使用 ":includes => [:brand]: 和 [item.as_json(includes: :brand)。也许是模型/迁移文件问题?编辑:没关系,它现在可以工作了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 2018-12-28
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多