2016-12-05 1 views
0

Ruby on Rails (특히 API 개발 용)를 배우고 있는데 도움이 필요합니다. 두 개의 테이블 "Brands"와 "Cars"가 있다고 가정 해 보겠습니다.
는 난 할 노력하고있어 기본적으로 :Ruby on Rails 5 : 중첩 된 json을 인쇄하는 방법

  1. 차를 가져 오기 대신 "brand_id : x"를 표시하는 '{: X, 이름 : 아이디 Y} 브랜드 = "를, 내가 표시 할 단지 중첩 된 JSON으로
  2. 각 차량에 대해 이렇게하십시오. 이제

, 내가 차를 도달 할 때, 그것은 나 제공 : 마이그레이션 파일 :

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 

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

내 파일은 다음을 포함

현재 내 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입니다. 나는 그것을 많이 봤지만이 문제를 해결하는 방법을 찾을 수 없었다.

답변

2

설명하는 방법 은 모델을 일련 번호로 지정합니다. 이 문제에 대한 강력한 솔루션을 제공하는 보석 (예 : 유서는 있지만 여전히 관련이있는 active_model_serializers)이 있지만 기본 사용 사례의 경우 Rails의 놀랍도록 강력한 기능인 as_json을 사용할 수 있습니다.

는 예를 들어, 표시 방법을 만들기 위해 브랜드 객체를 포함

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

또한 모델 수준에서 기본 as_json를 오버라이드 (override) 할 수 있지만, 그 해결책은 다른 발신자가 다른 직렬화와의 수준을 할 때 까다로운된다 세부 묘사. 당신이 묘사하고있는 것과 비슷한 또 다른 예를 들면 Include associated model when rendering JSON in Rails을 참조하십시오.

+0

빠른 응답을 보내 주셔서 감사합니다. 나는 그 코드를 시도했지만 작동하지 않는다. 나는 "brand_id"속성을 가진 아이템을 얻는다. ": includes => [: brand] :와 [item.as_json (includes : : 브랜드 포함)을 사용해 보았습니다. 모델/마이그레이션 파일 문제 일 가능성이 있습니까? 편집 : 신경 쓰지 마세요, 고맙습니다! –

관련 문제