私のRailsアプリケーションでは、以下のように同様の関係を設定しようとしています。 Rails Object Relationships and JSON RenderingネストされたJSONとオブジェクトの関係をレンダリングする
私はJSONがある示されるのと同じ方法でレンダリングされるようにしたい:
[
{
"modelb": {
"id": "1",
"modela": [insert the ModelA JSON for ID's 1, 2 and 3]
}
{
"modelb": {
"id": "2",
"modela": [insert the ModelA JSON for ID's 3, 4 and 5]
}
}
]
以下に示すように、私はすでに、モデルAのために必要なJSONを作成するコントローラを持っていますが、私はその情報を別のJSONセットに入れ子にするためにModelBモデルとコントローラを作成する方法や、どのModelAオブジェクトがModelBオブジェクトのどれに入るかを指定する方法はわかりません。
class JsonsController < ApplicationController
before_action :set_json, only: [:show, :update, :destroy]
# GET /jsons
# GET /jsons.json
def index
@jsons = Json.all
render json: @jsons
end
# GET /jsons/1
# GET /jsons/1.json
def show
render json: @json
end
# POST /jsons
# POST /jsons.json
def create
@json = Json.new(json_params)
if @json.save
render json: @json, status: :created, location: @json
else
render json: @json.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /jsons/1
# PATCH/PUT /jsons/1.json
def update
@json = Json.find(params[:id])
if @json.update(json_params)
head :no_content
else
render json: @json.errors, status: :unprocessable_entity
end
end
# DELETE /jsons/1
# DELETE /jsons/1.json
def destroy
@json.destroy
head :no_content
end
private
def set_json
@json = Json.find(params[:id])
end
def json_params
params.require(:json).permit(:text, :parent, :id)
end
end
任意のリソースまたはヘルプがあります。 @alexbezekとして
私はあなたが誤ってこのついて行くと思います。あなたのモデルはなぜJsonという名前ですか? ModelB.find(params [:id]) @ models.to_json(:include =>:modela) モデルコードを投稿すると、モデルのコードを投稿することができます。あなたがそれについてチャットしたいのであれば、気軽にメッセージにしてください –
私はそれをmodelBに変更しました。あなたが指定しているコードはどこに置くのですか?私のモデルコードは、参照されるリンクに示されているように、単純にhas_many、belongs_to関係です。ありがとう – Kevin