【发布时间】:2015-02-12 09:48:25
【问题描述】:
我尝试渲染一个正确格式的 json:
render json: {photo: @photo.as_json(with_thumbs_url: true)}
在我的模型中,我必须这样做:
def as_json(options={})
if options[:with_thumbs_url].present?
Jbuilder.encode do |json|
json.(self, :id, :beschreibung, :date, :art)
json.thumbs self.photo_thumbs.map{|e| e.file.url(:medium)}
end
end
end
我的问题是这样返回:
{photo: "{"id":288,"beschreibung":"Anfang","date" ...system/photos/6267/medium/136.webp?1413823129"]}"}
我不喜欢这个 JSON 的地方在于,Json 中的 photo 被渲染为字符串:
"{"id":288,"beschreibung":"
我宁愿不对其进行编码,例如:
{photo: {id: "288", beschreibung: "Anfang" ...
我会说问题出在我的代码上:encode:
Jbuilder.encode do |json|
所以为了解决我的问题,我尝试了:
Jbuilder.new do |json|
然后我得到一个错误:
render json: {photo: @photo.as_json(with_thumbs_url: true)}
wrong number of arguments (0 for 1..2)
我做错了什么以及如何修复我的代码?谢谢
【问题讨论】:
-
试试激活模型序列化 gem,很容易输出 json github.com/rails-api/active_model_serializers
标签: ruby-on-rails ruby ruby-on-rails-3 jbuilder