从as_json方法中排除数据

时间:2018-03-07 12:49:05

标签: ruby-on-rails json ruby

我的模型包含一些国家信息

class MyModel 
  include Mongoid::Document
  field :name, type: String
  field :country, as: :country, type: Country
end

MyModel.first.country

#<Country:0x007fc6a5d5f278 @data={"continent"=>"Asia", 
        "alpha2"=>"TH",
        "alpha3"=>"THA",
        "country_code"=>"66",
        "currency"=>"THB",
        "international_prefix"=>"001",
        "ioc"=>"THA", "latitude"=>"15 00 N",
        "longitude"=>"100 00 E", "name"=>"Thailand",
        "names"=>["Thailand", "Thaïlande", "Tailandia", "タイ"],
        "translations"=>{"en"=>"Thailand",
                         "it"=>"Tailandia",
                         "de"=>"Thailand",  
                         "fr"=>"Thaïlande",
                         "es"=>"Tailandia",
                         "ja"=>"タイ",
                         "nl"=>"Thailand",  
                         "ru"=>"Таиланд"},
        "national_destination_code_lengths"=>[2],
        "national_number_lengths"=>[9, 10],
        "national_prefix"=>"0", "number"=>"764",
        "region"=>"Asia", "subregion"=>"South-Eastern Asia",
        "un_locode"=>"TH", "languages"=>["th"], "nationality"=>"Thai"}>

致电MyModel.first.to_json(only: [:name, :country])只应返回alpha2translationsnames

我该如何实现? 我尽量避免为此编写额外的方法。

编辑:

预期输出如下:

MyModel.first

{"name": "ModelName",
 "country": {"alpha2"=> "TH", 
             "name" => "Thailand",
             "names"=> ["Thailand", "Thaïlande", "Tailandia", "タイ"]
 }

1 个答案:

答案 0 :(得分:0)

您可以覆盖模型的list indices must be integers, not str方法以获得所需的结果。

as_json

现在,您可以通过在模型

上调用class MyModel def as_json(options = {}) super(only: [:name]).merge( country: country.data.slice("alpha2", "unofficial_names", "translations") ) end end 来获取数据
as_json

希望它有所帮助!