【发布时间】:2013-02-03 00:32:30
【问题描述】:
我正在开发一个使用某种继承结构的项目......基类是..
# /app/models/shape.rb
class Shape < ActiveRecord::Base
acts_as_superclass # https://github.com/mhuggins/multiple_table_inheritance
end
子类是...
# /app/models/circle.rb
class Circle < ActiveRecord::Base
inherits_from :shape
end
这是一个显示继承结构的图形。
对于这些模型,我正在尝试使用RABL gem 创建一个 API。以下是相关的控制器...
# /app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < InheritedResources::Base
load_and_authorize_resource
respond_to :json, except: [:new, :edit]
end
...
# /app/controllers/api/v1/shapes_controller.rb
class Api::V1::ShapesController < Api::V1::BaseController
actions :index
end
end
...
# /app/controllers/api/v1/circles_controller.rb
class Api::V1::CirclesController < Api::V1::BaseController
def index
@circles = Circle.all
end
def show
@circle = Circle.find(params[:id])
end
end
我按照Railscast #322 of Ryan Bates 中的建议创建了一个show 模板。看起来是这样的……
# /app/views/circles/show.json.rabl
object @circle
attributes :id
当我通过http://localhost:3000/api/v1/circles/1.json 请求圈子时,会显示以下错误消息...
模板丢失
缺少模板 api/v1/circles/show, api/v1/base/show, inherit_resources/base/show, 应用程序/show with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :arb, :haml, :rabl]}。
我需要如何设置模板才能使用继承的资源?
部分成功
我提出了以下观点。我还设法实现了模型的继承结构以保持代码 DRY。
# views/api/v1/shapes/index.json.rabl
collection @shapes
extends "api/v1/shapes/show"
...
# views/api/v1/shapes/show.json.rabl
object @place
attributes :id, :area, :circumference
...
# views/api/v1/circles/index.json.rabl
collection @circles
extends "api/v1/circles/show"
...
# views/api/v1/circles/show.json.rabl
object @circle
extends "api/v1/shapes/show"
attributes :radius
if action_name == "show"
attributes :shapes
end
这将为圈子输出所需的 JSON(index 操作):
# http://localhost:3000/api/v1/cirles.json
[
{
"id" : 1,
"area" : 20,
"circumference" : 13,
"radius" : 6
},
{
"id" : 2,
"area" : 10,
"circumference" : 4,
"radius: 3
}
]
但它确实不输出关联的 shapes 与所有属性出于某种原因...
注意:Shape 模型上有一个我之前没有提到的关联。
# http://localhost:3000/api/v1/cirles/1.json
{
"id" : 1,
"area" : 20,
"circumference" : 13,
"radius" : 6,
"shapes" : [
{
"id" : 2,
"created_at" : "2013-02-09T12:50:33Z",
"updated_at" : "2013-02-09T12:50:33Z"
}
]
},
【问题讨论】:
标签: ruby-on-rails json inheritance rabl inherited-resources