代码之家  ›  专栏  ›  技术社区  ›  Jan

从as\U json方法中排除数据

  •  0
  • Jan  · 技术社区  · 8 年前

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

    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]) 应仅返回 alpha2 , translations names

    我如何才能做到这一点? 我尽量避免为此编写额外的方法。

    编辑:

    预期输出如下:

    MyModel。第一

    {"name": "ModelName",
     "country": {"alpha2"=> "TH", 
                 "name" => "Thailand",
                 "names"=> ["Thailand", "Thaïlande", "Tailandia", "タイ"]
     }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Ashik Salman    8 年前

    您可以覆盖 as_json 方法来获取所需的结果。

    class MyModel
      def as_json(options = {})
        super(only: [:name]).merge(
          country: country.data.slice("alpha2", "unofficial_names", "translations")
        )
      end
    end
    

    现在您可以通过调用 as\U json 在模型上

    MyModel.first.as_json
    

    希望有帮助!