2013-02-03 40 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