我正在开发一个使用某种继承结构的项目......基类是..
# /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
我按照Ryan Bates 的 Railscast #322 中的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、inherited_resources/base/show、application/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"
}
]
},