我想傳遞一個對象(當前用戶)在渲染集合的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渲染器知道當前用戶的更優雅的方式?
感謝, 衛
謝謝! to_json是關鍵。爲了澄清,to_a是爲了防止錯誤,ActiveSupport :: JSON :: Encoding :: CircularReferenceError(http://osdir.com/ml/RubyonRailsTalk/2010-08/msg00176.html)。 – yayitswei 2010-09-14 23:23:15