as_json with:除了不工作

时间:2012-07-09 16:29:24

标签: ruby-on-rails json

我正在尝试格式化json响应,删除不需要的字段以获得较小的响应(即created_at和updated_at)

我目前正在这样做:

friends = @user.friends
friends.each do |f|
  f[:name] = f.user.username # adding arbitrary attribute needed in the response
end
render :json => friends.as_json(:except => [:created_at, :updated_at])

created_at和updated_at仍然包含在响应中,我做错了什么?

1 个答案:

答案 0 :(得分:2)

:except不会处理嵌套在数组中的属性。你可以在实例上使用它:

friends = @user.friends.map do |f|
  f[:name] = f.user.username # adding arbitrary attribute needed in the response
  f.as_json(:except => [:created_at, :updated_at]
end
render :json => friends