【发布时间】:2016-12-05 18:47:31
【问题描述】:
我正在学习 Ruby on Rails(专门用于 API 开发),我需要一些帮助。
假设我们有 2 个表,“Brands”和“Cars”。
我要做的基本上是:
- 买车:我不想显示“brand_id: x”,而是显示“brand = { id: X, name: Y}”,就像嵌套的 JSON 一样。
- 为每辆车执行此操作。
现在,当我试图上车时,它给了我:
{
"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