在输出为json之前过滤模型的属性 [英] Filter a model's attributes before outputting as json

查看:103
本文介绍了在输出为json之前过滤模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我需要将我的模型输出为json,一切都很好.但是,某些属性需要通过一些辅助方法(例如number_to_human_size)进行过滤来美化".我将如何去做?

Hey guys, I need to output my model as json and everything is going fine. However, some of the attributes need to be 'beautified' by filtering them through some helper methods, such as number_to_human_size. How would I go about doing this?

换句话说,假设我有一个名为bytes的属性,我想将其传递给number_to_human_size并将那个结果输出到json.

In other words, say that I have an attribute named bytes and I want to pass it through number_to_human_size and have that result be output to json.

如果可能的话,我也想修剪"什么作为json输出,因为我只需要一些属性.这可能吗?有人可以给我一个例子吗?我真的很感激.

I would also like to 'trim' what gets output as json if that's possible, since I only need some of the attributes. Is this possible? Can someone please give me an example? I would really appreciate it.

初步搜索结果暗示了有关as_json的某些信息,但我找不到与我的情况有关的实际示例.如果这真的是解决方案,我将不胜感激一个例子.

Preliminary search results hint at something regarding as_json, but I can't find a tangible example pertaining to my situation. If this is really the solution, I would really appreciate an example.

研究:似乎我可以使用to_json的选项来明确说明我想要的属性,但是我仍然需要弄清楚如何美化"或过滤"在将某些属性作为json输出之前,先将它们传递给帮助程序.

Research: It seems I can use to_json's options to explicitly state which attributes I want, but I'm still in need of figuring out how to 'beautify' or 'filter' certain attributes by passing them through a helper before they're output as json.

我要为单个json模型创建一个局部模型,即_model.json.erb,然后为我正在使用的操作创建另一个局部模型,并在其中简单地用对象集合来呈现局部模型吗?好像跳了一圈.我想知道是否存在更直接/原始的方式来更改模型的json表示形式.

Would I create a partial for a single json model, so _model.json.erb, and then create another one for the action I'm using, and within that simply render the partial with the collection of objects? Seems like a bunch of hoops to jump through. I'm wondering if there's a more direct/raw way of altering the json representation of a model.

推荐答案

您的模型可以覆盖as_json方法,Rails在呈现json时会使用该方法:

Your model can override the as_json method, which Rails uses when rendering json:

# class.rb
include ActionView::Helpers::NumberHelper
class Item < ActiveRecord::Base
  def as_json(options={})
    { :state => state, # just use the attribute when no helper is needed
      :downloaded => number_to_human_size(downloaded)
    }
  end
end

现在您可以在控制器中调用render :json:

Now you can call render :json in the controller:

@items = Item.all
# ... etc ...
format.json { render :json => @items }

Rails将为@items的每个成员调用Item.as_json,并返回一个JSON编码的数组.

Rails will call Item.as_json for each member of @items and return a JSON-encoded array.

这篇关于在输出为json之前过滤模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆