簡體   English   中英

Rails Serializer不過濾數據

[英]Rails Serializer not filtering data

我試圖在Rails API應用程序中由API返回的JSON對象上使用Rail的Serializer。 我需要驗證,攝取API,過濾數據,並重新廣播過濾后的數據。 無需查看。

為了過濾數據,我正在嘗試實現Serializer - 很明顯我沒有正確設置它。 我可以看到它正在工作並且到位,因為它在它返回的數據前面添加了初始對象(參見下面的數據:序列化對象以kobo_data )。 但它正在返回所有數據字段,而不僅僅是我要調用的字段。 在這種情況下,我試圖只返回字段prikey ,但它返回所有數據字段。

我試圖在類似的線程中解決問題( Rails中的ActiveModel :: Serializer - 在JSON結果中忽略的序列化器方法rails活動模型序列化器沒有做任何事情在Rails中使用ActiveModel :: Serializer - json和index之間的JSON數據不同響應 ),但因為我沒有一個html的看法,我不知道這可能與在最后一個環節中提到的問題。 但是我做過的另一個教程( https://thesocietea.org/2015/03/building-a-json-api-with-rails-part-2-serialization/ )在沒有視圖的Rails-API應用程序中使用了序列化所以我猜它不是。

關於我做錯了什么以及如何解決它的任何建議?

模型:

class KoboApi < ActiveRecord::Base    
    require 'rest_client'
    USERNAME = ENV['KOBO_API_USER']
    PASSWORD = ENV['KOBO_API_PWD']
    SURVEY = ENV['KOBO_API_SURVEY']
    # API_BASE_URL = "https://kc.kobotoolbox.org/api/v1/"
    API_BASE_URL = "https://sg.smap.com.au/api/v1"
    def self.get_api_info
        uri = "#{API_BASE_URL}/data/#{SURVEY}?format=json"
        rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)
        response = rest_resource.get
        JSON.parse response
    end
end

調節器

class KoboDataController < ApplicationController
    def index
        @kobo_info = KoboApi.get_api_info
        render json: @kobo_info
    end
end

應用控制器

class ApplicationController < ActionController::API
    include ActionController::Serialization
end

kobo_api_serializer.rb

class KoboApiSerializer < ActiveModel::Serializer
  attributes :prikey
end

寶石文件

source 'https://rubygems.org'

gem 'active_model_serializers', '~> 0.8.3'
gem 'rest-client'
gem 'pg'
gem 'rails', '4.2.5.1'
gem 'rails-api'
gem 'spring', :group => :development

# gem for environment variables
gem 'dotenv-rails', :groups => [:development, :test]
gem 'figaro'

數據已返回

{"kobo_data":[{"prikey":"1","Upload Time":"2016-06-17 11:11:38.802+00","Version":"1","Complete":"t","Survey Notes":"","Location Trigger":"","deviceid":"webworm"....[data truncated]

我剛跟一個跟我說過我遇到的問題的人談過,並不是所有與我上面發布的代碼有關。 我在這里發布一些細節。 我確定還有其他方法可以解決這個問題,但這就是我們如何解決這個問題。 希望它有用。

主要問題:沒有each_serializer

特別與上面發布的語言相關:我沒有在我的模型中的render語句中包含對each_serializer引用。 這個問題在這里引用了這個問題: rails active model serializer沒有做任何事情

調節器

class KoboDataController < ApplicationController
  def index
    @kobo_info = KoboApi.get_api_info
    @kobo_info.each do |kobo_info|
      begin
        #this pulls in new records that have been added to the api and adds them to the database.  it doesn't pull in records from the api that are already in the db
        KoboApi.find_or_create_by(lemurs_quantity: kobo_info['lemurs_quantity'], month_and_year:  Date.parse(kobo_info['month_and_year']))
          # some of my records don't have valid date values, so `rescue` is added to keep rails from returning a `notfound` page.
          # quick tutorial here:  http://www.rubytutorial.io/rails-rescue_from/
      rescue
        puts "rescued"
      end
    end
    # I needed to update my render logic.
    # see addition of `each_serializer` here.
    # @kobo_info has also changed to KoboApi.all as well.
    render(
      json: KoboApi.all,
      each_serializer: KoboApiSerializer
    )
  end
end

如果我的數據庫配置正確,這應該已經為我修復了。

另外,為了防止我使用的Active Model Serializers出現問題,我們更新了我的gem文件,用以下內容替換了我的行( gem 'active_model_serializers', '~> 0.8.3' ):

gem 'active_model_serializers', :git => 'git://github.com/AskNative/active_model_serializers.git', :branch => '0-8-stable'  

第二個問題:不正確的數據庫表名

但是,我創建的雙字表名有問題。 我用camelCase名稱結構創建了我的表,rails期望使用separate_words(即:使用下划線)。

你可以看到這里的表名是koboApis

原始遷移

class KoboApis < ActiveRecord::Migration
  def change
    create_table :koboApis do |t|
      t.integer :lemurs_quantity
      t.date  :month_and_year
      t.text :_geolocation
      t.text :lemur_category
    end
  end
end

您可以在我的原始架構中看到表名確實是kobo_apis ,而不是`koboApis'。

模式

ActiveRecord::Schema.define(version: 20160620063545) do

  create_table "kobo_apis", force: :cascade do |t|
    t.integer "lemurs_quantity"
    t.date    "month_and_year"
    t.text    "_geolocation"
    t.text    "lemur_category"
  end
end

由於這個原因,表Rails預計甚至不存在。

我們通過在終端上運行第二次遷移來修復此問題: rails g migration RenameOldTableToNewTable 然后我將此邏輯添加到新的遷移文件中: rename_table :koboApis, :kobo_apis 整個遷移文件在這里:

更新遷移文件

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
     rename_table :koboApis, :kobo_apis
  end
end

我運行了rake db:drop db:create db:migrate來更新所有內容,然后我的Rails Api頁面正確呈現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM