2012-09-05 39 views
1

如果我使用node()方法在RABL中創建子節點,如何控制呈現的屬性?RABL - 子節點內的屬性

的JSON輸出是這樣的:

[ 
    { 
     "location": { 
      "latitude": 33333, 
      "longitude": 44444, 
      "address": "xxxxxxx", 
      "title": "yyyy", 
      "url": "http://www.google.com", 
      "rate": { 
       "created_at": "2012-09-02T11:13:13Z", 
       "id": 1, 
       "location_id": 1, 
       "pair": "zzzzzz", 
       "updated_at": "2012-09-02T12:55:28Z", 
       "value": 1.5643 
      } 
     } 
    } 
] 

我想擺脫created_at,的updated_at和LOCATION_ID屬性。

我有這在我的視圖文件:

collection @locations 
attributes :latitude, :longitude, :address, :title, :url 
node (:rate) do 
    |location| location.rates.where(:pair => @pair).first 
end 

我嘗試使用的部分和「延長」的方法,但它完全搞砸的事情了。此外,我嘗試添加屬性的塊,但它不起作用(輸出是在屬性中指定,但它沒有顯示每個屬性的值)。

謝謝!

回答

1

您的代碼:location.rates.where(:pair => @pair).first返回整個Rate對象。如果你想要特定字段(例如:所有的,除了create_at,的updated_at等),那麼你有兩個選擇:

手動描述節點哈希():

node (:rate) do |location| 
    loc = location.rates.where(:pair => @pair).first 
    { :pair => loc.pair, :value => loc.value, etc... } 
end 

或者你能做到這

node (:rate) do |location| 
    location.rates.where(:pair => @pair).select('pair, value, etc...').first 
end 

...作爲一個方面說明,我應該說,在你看來把邏輯(rates.where)不是最好的做法。查看您的控制器是否可以使用Rate模型爲視圖執行此操作。

+0

謝謝...我最終用'手動'解決方案。在視圖中執行此邏輯的原因是,我必須通過每個位置對象並查找速率,然後輸出兩者。我試圖想到在控制器中這樣做,但它似乎太複雜了(我想這將涉及創建一些新的對象來保存每個位置和相應的費率)..所以我決定爲了簡單在視圖中執行它 – Imme22009

1

您將無法在節點塊內使用attributes,因爲「self」中仍存在根對象或集合,因此您的情況爲@locations。又見RABL wiki: Tips and tricks (When to use Child and Node)

在節點塊,你可以簡單地只列出的屬性,你的興趣在創建自定義的響應:

在:

node :rate do |location| 
    rate = location.rates.where(:pair => @pair).first 
    {:id => rate.id, :location_id => rate.location_id, :value => rate.value} 
end 

您也可以使用部分嘗試的方法app/views/rates/show.json.rabl

object @rate 
attributes :id, :location_id, :value 

然後在你的@locations Rabl的看法:

node :rate do |location| 
    rate = location.rates.where(:pair => @pair).first 
    partial("rates/show", :object => rate) 
end 
+0

謝謝....我試過你的方法使用部分,但它沒有工作 – Imme22009

+0

真的嗎?同樣的方法適用於我。你得到的錯誤是什麼? –