【发布时间】:2016-09-16 23:00:03
【问题描述】:
我正在尝试在我的 Rails 应用程序中建立类似于以下 SO 问题中的关系。 Rails Object Relationships and JSON Rendering
我希望我的 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,如下所示,但我不知道如何制作 ModelB 模型和控制器以便将该信息嵌套到另一组 JSON 中,或者如何指定哪个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
任何资源或帮助将不胜感激。
【问题讨论】:
-
我认为您的处理方式不正确。为什么你的模型命名为 Json?它应该是 ModelB 然后你可以做 @models = ModelB.find(params[:id]) 然后 @models.to_json(:include => :modela) 发布你的模型代码会有所帮助。如果您想聊聊,请随时留言
-
我已将其更改为modelB,我将把您指定的代码放在哪里?我的模型代码只是一个 has_many ,belongs_to 关系,如引用的链接所示。谢谢
标签: javascript ruby-on-rails ruby json