2015-01-26 69 views
0

我想用两种不同的方式让我的json呈现。现在我有as_json方法重写来显示JSON形式这样一个完整的对象:两种不同的as_json方法

{ 
    prop1: stuff, 
    prop2: stuff, 
    innerthings: { 
     { 
      prop1:stuff, 
      prop2:stuff 
     } 
     { 
      prop1:stuff, 
      prop2:stuff 
     } 
    } 
} 

而且as_json样子:

#Renders json 
    def as_json(options={}) 
    super(
     :except => [:created_at, :updated_at], 
     :include => [{:innerthings = > { 
       :except => [:created_at, :updated_at] 
}}] 

    ) 
    end 

我也想有第二个选择渲染是这样的:当下面的代码是用来

{ 
    prop1:stuff, 
    prop2:stuff, 
    countinnerthings:10 
} 

目前,我得到的第一个渲染:

respond_to do |format| 
    format.json { render json: @thing} 
end 

我还希望能够像as_list一样渲染,我可以在像下面这样的情况下使用它来呈现对象的简单列表。

respond_to do |format| 
    format.json { render json: @things.as_list } 
end 

有没有一种简单的方法可以在rails上做到这一点?

回答

1

你可以只定义一个as_list方法

def as_list 
    { 
    prop1: "stuff" 
    } 
end 

如果您需要使用包括等,你可以从你的at_list方法调用as_json。如前所述,串行器通常是更好的选择。

+0

这有效,但我不得不修改我的JSON做类似如果选项== nil || options.count == 0 basicjson else super(选项)结束 – steventnorris 2015-01-26 20:07:21

3

而不是滚动自己的as_json方法。看看ActiveModel Serializers。我认为它会满足你的用例并帮助组织你的代码。

+0

我见过ActiveModel串行器,看看他们的优点;不过,这是一个遗留系统,在序列化器的理解之前就已经开发出来了,目前它不是迁移的选项。 – steventnorris 2015-01-26 19:43:40