2013-02-03 52 views
0

我上使用一些继承结构...的基类是一个项目的工作..Rails的:与遗传模型结构Rabl的模板

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

我创建了一个show模板中Railscast #322 of Ryan Bates建议。它看起来像这样...

# /app/views/circles/show.json.rabl 
object @circle 
attributes :id 

当我请求通过http://localhost:3000/api/v1/circles/1.json显示以下错误消息的圈子......

模板丢失

缺少模板API/V1 /圈/ show,api/v1/base/show, inherited_resources/base/show,application/show with {:locale => [:en], :formats => [:html],:handlers => [:erb, :builder,:arb,:haml,:rabl]}。

我该如何设置模板才能使用继承的资源?


部分成功

我想出了以下几点看法。我还设法实现了模型的继承结构,以使代码保持干爽。

# 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

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

对于第二个问题,这听起来像你说每个圆圈has_many关联的形状。在这种情况下,我相信类似以下内容应该给你想要的东西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 
+0

听起来很合理。我没有看到。我会查的。 – JJD

+0

谢谢你的主要解决方案。你可否请你注意一下我试图描述的细节问题? – JJD

+0

您的'views/api/v1/circles/show.json.rabl'模板在'if action_name =='show''里面,我相信这会阻止shapes属性显示在索引操作中。 – cbascom