2010-09-14 68 views
1

我想傳遞一個對象(當前用戶)在渲染集合的json時使用。通過選項散列將值傳遞給as_json?

respond_to do |format| 
    format.html # index.html.erb 
    format.xml { render :xml => @items } 
    format.json { render :json => @items.to_a.as_json(:user => current_user) } 
end 

但是,這似乎沒有任何作用,因爲選項[:用戶]在as_json方法中爲零。

JSON_ATTRS = ['id', 'created_at', 'title', 'content'] 
def as_json(options={}) 
    # options[:user] is nil! 
    attributes.slice(*JSON_ATTRS).merge(:viewed => viewed_by?(options[:user])) 
end 

任何人都知道爲什麼這不起作用,或者可以建議讓json渲染器知道當前用戶的更優雅的方式?

感謝, 衛

回答

1

您是在陣列(@items.to_a)調用as_json,你確定這是你想要的嗎? 如果您試圖在模特上打電話,那麼您需要執行類似@items.to_a.map{|i| i.to_json(:user => current_user)}的操作(並且您可能不需要to_a)。

而你應該打電話的是to_json。它會調用as_json來獲得你的屬性,傳遞你提供的任何選項,但返回一個正確格式的json字符串(as_json返回一個ruby對象)。

+0

謝謝! to_json是關鍵。爲了澄清,to_a是爲了防止錯誤,ActiveSupport :: JSON :: Encoding :: CircularReferenceError(http://osdir.com/ml/RubyonRailsTalk/2010-08/msg00176.html)。 – yayitswei 2010-09-14 23:23:15

0

順便說一句,如果你想傳遞到「兒童」協會的選項,我發現這個工作(至少在mongo_mapper支持的項目):

def as_json(options={}) 
    { 
     :field1 => self.field1, 
     :field2 => self.field2, 
     :details => self.details.map{|d| d.to_json(options)} 
    } 
end