Rails:具有继承模型结构的Rabl模板

时间:2013-02-03 00:32:30

标签: ruby-on-rails json inheritance rabl inherited-resources

我正在开发一个使用一些继承结构的项目......基类是..

# /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

这是一个显示继承结构的图形。

Class model

对于这些模型,我尝试使用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,   inherited_resources / base / show,application / show with {:locale =&gt; [:en],   :formats =&gt; [:html],:handlers =&gt; [: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

这会为圈子(index操作)输出所需的JSON:

# 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"
    }
  ]
},

1 个答案:

答案 0 :(得分:1)

根据您提供的数据,您将模板放在/app/views/circles中。错误告诉您需要将它们放在/app/views/api/v1/circles而不是我相信。

对于第二个问题,听起来你说每个圆圈都有相关的形状。在这种情况下,我相信以下内容应该为views/api/v1/circles/show.json.rabl提供您想要的内容:

# views/api/v1/circles/show.json.rabl
object @circle
extends 'api/v1/shapes/show'
attributes :radius
child(:shapes) do
  extends 'api/v1/shapes/show'
end