简体   繁体   English

Rails Serializer不过滤数据

[英]Rails Serializer not filtering data

I am trying to use Rail's Serializer on a JSON object being returned by an API in a Rails API app. 我试图在Rails API应用程序中由API返回的JSON对象上使用Rail的Serializer。 I need to authenticate, ingest the API, filter the data, and rebroadcast the filtered data. 我需要验证,摄取API,过滤数据,并重新广播过滤后的数据。 No view is required. 无需查看。

To filter the data, I am trying to implement the Serializer - it's clear I haven't set it up correctly though. 为了过滤数据,我正在尝试实现Serializer - 很明显我没有正确设置它。 I can see it is working and in place because it is adding the initial object in front of the data it is returning (see data below: serialized object starts with kobo_data ). 我可以看到它正在工作并且到位,因为它在它返回的数据前面添加了初始对象(参见下面的数据:序列化对象以kobo_data )。 But it is returning all the fields of data, not just the fields I'm trying to call. 但它正在返回所有数据字段,而不仅仅是我要调用的字段。 In this case I'm trying to return just the field prikey , but it is returning all the fields of data. 在这种情况下,我试图只返回字段prikey ,但它返回所有数据字段。

I've tried to address issues in similar threads to this ( ActiveModel::Serializer in Rails - serializer methods ignored in JSON result , rails active model serializer not doing anything , Using ActiveModel::Serializer in Rails - JSON data differs between json and index response ), although since I don't have a .html view, I wonder if this might be related to the issue mentioned in the last link. 我试图在类似的线程中解决问题( Rails中的ActiveModel :: Serializer - 在JSON结果中忽略的序列化器方法rails活动模型序列化器没有做任何事情在Rails中使用ActiveModel :: Serializer - json和index之间的JSON数据不同响应 ),但因为我没有一个html的看法,我不知道这可能与在最后一个环节中提到的问题。 But another tutorial I"ve done ( https://thesocietea.org/2015/03/building-a-json-api-with-rails-part-2-serialization/ ) employs serialization in a Rails-API app without a view, so I'm guessing it's not. 但是我做过的另一个教程( https://thesocietea.org/2015/03/building-a-json-api-with-rails-part-2-serialization/ )在没有视图的Rails-API应用程序中使用了序列化所以我猜它不是。

Any suggestions on what I'm doing wrong and how I can fix it? 关于我做错了什么以及如何解决它的任何建议?

Model: 模型:

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

Controller 调节器

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

Application Controller 应用控制器

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

kobo_api_serializer.rb kobo_api_serializer.rb

class KoboApiSerializer < ActiveModel::Serializer
  attributes :prikey
end

Gem file 宝石文件

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'

Data returned 数据已返回

{"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]

I just spoke with someone who walked me through the problem I was having, not all of which was related to the code I posted above. 我刚跟一个跟我说过我遇到的问题的人谈过,并不是所有与我上面发布的代码有关。 Am posting some details here. 我在这里发布一些细节。 Am sure there are other ways to fix this, but this is how we covered it. 我确定还有其他方法可以解决这个问题,但这就是我们如何解决这个问题。 Hope it's helpful. 希望它有用。

Primary Issue: no each_serializer 主要问题:没有each_serializer

Specifically related to the language as posted above: I was not including reference to each_serializer in my render statement in my model. 特别与上面发布的语言相关:我没有在我的模型中的render语句中包含对each_serializer引用。 This issue is referenced in this thread here as well: rails active model serializer not doing anything . 这个问题在这里引用了这个问题: rails active model serializer没有做任何事情

controller 调节器

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

If my database had been configured correctly, this should have fixed it for me. 如果我的数据库配置正确,这应该已经为我修复了。

Also, just in case there was an issue with the Active Model Serializers i was using, we updated my gem file to replace the line I had ( gem 'active_model_serializers', '~> 0.8.3' ) with the following: 另外,为了防止我使用的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'  

Second Issue: incorrect db table name 第二个问题:不正确的数据库表名

However, I had an issue with the two-word table name I had created. 但是,我创建的双字表名有问题。 I had created my table with a camelCase name structure, and rails was expecting separated_words (ie: with underscore). 我用camelCase名称结构创建了我的表,rails期望使用separate_words(即:使用下划线)。

You can see the table name here is koboApis : 你可以看到这里的表名是koboApis

original migration 原始迁移

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

You can see in my original schema that the table name is indeed kobo_apis , and not `koboApis'. 您可以在我的原始架构中看到表名确实是kobo_apis ,而不是`koboApis'。

schema 模式

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

The table Rails was expecting didn't even exist because of this. 由于这个原因,表Rails预计甚至不存在。

We fixed this by running a second migration at the terminal: rails g migration RenameOldTableToNewTable . 我们通过在终端上运行第二次迁移来修复此问题: rails g migration RenameOldTableToNewTable I then added this logic to the new migration file: rename_table :koboApis, :kobo_apis . 然后我将此逻辑添加到新的迁移文件中: rename_table :koboApis, :kobo_apis Entire migration file here: 整个迁移文件在这里:

update migration file 更新迁移文件

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

I ran rake db:drop db:create db:migrate to update everything, and then my Rails Api page rendered correctly. 我运行了rake db:drop db:create db:migrate来更新所有内容,然后我的Rails Api页面正确呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM