Ich lerne Ruby on Rails (speziell für API-Entwicklung) und ich brauche etwas Hilfe bei etwas. Sagen wir, wir haben 2 Tische, "Marken" und "Autos".
Was ich versuche ist im Grunde zu tun:Ruby on Rails 5: Wie verschachtelte JSON gedruckt werden
- ein Auto holen: Statt "brand_id: x" die Anzeige, ich will, um "Marke = {id: X, Name: Y}", gerade als verschachtelter JSON.
- Tun Sie das für jedes Auto.
Jetzt, wenn ich versuche, ein Auto zu erreichen, bringt es mich:
{
"id": 1,
"name": "Veneno",
"brand_id": 1,
"created_at": "2016-12-03T21:47:01.000Z",
"updated_at": "2016-12-03T21:47:01.000Z"
}
Meine Dateien enthalten die folgenden: Migration Dateien:
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
Modelle:
class Brand < ApplicationRecord
has_many :items
end
class Item < ApplicationRecord
belongs_to :brand
end
Momentan ist meine 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
Vielen Dank! Ich bin rund um die Uhr online, um weitere Informationen zu diesem Problem zu geben. Ich habe viel gegooglet, aber ich konnte nicht herausfinden, wie ich das beheben kann.
Vielen Dank für die schnelle Antwort! Ich habe gerade diesen Code ausprobiert, aber funktioniert nicht, ich bekomme das Element mit dem Attribut "brand_id". Versucht mit ": includes => [: brand]: und mit dem [item.as_json (beinhaltet:: brand). Vielleicht ist es ein Modell/Migration Datei Problem? EDIT: Nevermind, es funktioniert jetzt. Vielen Dank! –