Ruby on Rails (특히 API 개발 용)를 배우고 있는데 도움이 필요합니다. 두 개의 테이블 "Brands"와 "Cars"가 있다고 가정 해 보겠습니다.
는 난 할 노력하고있어 기본적으로 :Ruby on Rails 5 : 중첩 된 json을 인쇄하는 방법
- 차를 가져 오기 대신 "brand_id : x"를 표시하는 '{: X, 이름 : 아이디 Y} 브랜드 = "를, 내가 표시 할 단지 중첩 된 JSON으로
- 각 차량에 대해 이렇게하십시오. 이제
, 내가 차를 도달 할 때, 그것은 나 제공 : 마이그레이션 파일 :
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입니다. 나는 그것을 많이 봤지만이 문제를 해결하는 방법을 찾을 수 없었다.
빠른 응답을 보내 주셔서 감사합니다. 나는 그 코드를 시도했지만 작동하지 않는다. 나는 "brand_id"속성을 가진 아이템을 얻는다. ": includes => [: brand] :와 [item.as_json (includes : : 브랜드 포함)을 사용해 보았습니다. 모델/마이그레이션 파일 문제 일 가능성이 있습니까? 편집 : 신경 쓰지 마세요, 고맙습니다! –