【问题标题】:postgres_ext/serializers help... seems so simple, but can't get anything to work as describedpostgres_ext/serializers help... 看起来很简单,但无法按照描述的那样工作
【发布时间】:2015-10-27 23:01:01
【问题描述】:

https://github.com/dockyard/postgres_ext-serializers

这似乎很容易设置,但在将 JSON 从 rails 移动到 postgres 方面,我似乎无法获得任何基本功能。我尝试在我的 ams init、我的特定序列化程序和我的模型中包含以下内容,但它似乎从未被激活。

我在 Rails 4.2.3 和 Ruby 2.2 上

这是我尝试添加到多个文件的内容:

需要'postgres_ext/serializers'

非常感谢您的帮助,我知道我一定遗漏了一些明显的东西。

更新:为了提供更多背景信息,您阅读了此 gem 的 README.md 说明,它只是说“

只需要 'postgres_ext/serializers' 并使用 像往常一样使用 ActiveModel::Serializers!

所以我在我的 application.rb 中添加了 require 'postgres_ext/serializers',对序列化程序进行了小修改以查看它是否有效:

class UserSerializer < ActiveModel::Serializer

  cached false

  attributes :id, :username, :location, :full_name

  def full_name
    "#{object.first_name} #{object.last_name}"
  end

  def full_name__sql
    "first_name || ' ' || email"
  end

end

然后我会在我的 Rails 控制台中运行以下命令:

users = User.first(10)
ActiveModel::ArraySerializer.new(users, each_serializer: UserSerializer).to_json

但 __sql 全名属性从未显示,而且它从 postgres 中提取数据似乎与以前没有任何不同。

这就是我的 application.rb 的样子:

# require 'postgres_ext/serializers' ### Doesn't work here

require File.expand_path('../boot', __FILE__)

require 'rails/all'

require 'postgres_ext/serializers'

Bundler.require(*Rails.groups)

module Baller
  class Application < Rails::Application
    # Do not swallow errors in after_commit/after_rollback callbacks.
    config.active_record.raise_in_transactional_callbacks = true

    # From: http://www.benfranklinlabs.com/where-to-put-rails-modules/
    # config.autoload_paths += %W(#{config.root}/lib) # add this line
    config.autoload_paths += %W(#{config.root}/lib)
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
  end
end

谢谢!

【问题讨论】:

  • 请在您的问题中添加确切的错误消息。究竟什么是行不通的,你怎么知道的?
  • @EugZol 刚刚在我的帖子中添加了更多细节。感谢收看!

标签: ruby-on-rails ruby-on-rails-4 activemodel serialization


【解决方案1】:

您是否尝试过将此require 'postgres_ext/serializers' 添加到您的config/application.rb 的顶部。我想当它更改 Postgres 驱动程序时,这需要在其他任何事情之前被要求。

更新以回答您的更新:

def full_name__sql
  "first_name || ' ' || email"
end

应该是:

def self.full_name__sql
 "first_name || ' ' || email"
end

来自文档:

... 通过查找具有相同名称的类方法和 后缀__sql ...

【讨论】:

  • 是的,但是当我将它包含在最顶部时出现错误:gems/active_model_serializers-0.8.0/lib/active_model_serializers.rb:12:in `': uninitialized常量 Rails::Railtie (NameError) 我可以在文件中包含它以便它工作的最早的时​​间是: require 'rails/all' 非常感谢任何帮助!
  • 那么当你在 rails/all 之后包含它时它不起作用吗?我认为在那之后应该是正确的地方。
  • 当我在 rails/所有控制台加载后包含它时没有错误,但它在 postgres_ext/serializers 似乎没有被激活或连接的意义上不起作用。
  • 阅读我更新的帖子。该方法应该是一个类方法。
  • 类方法不是问题,因为我已经尝试了两种方法......结果被序列化的变量需要是 ActiveRecord::Relation 类型......并且因为 users = User .first(10) 返回用户对象数组而不是 ActiveRecord::Relation,它不会触发代码。因此,我将测试更改为使用 User.where("id>100").limit(10) 似乎它正在尝试工作,但现在我收到一个新错误“错误数量的争论”......我会如果我想不通,请打开一个新的 SE 帖子。感谢您的帮助!
猜你喜欢
  • 2014-03-20
  • 1970-01-01
  • 2017-12-31
  • 2018-05-31
  • 2020-04-04
  • 2017-10-31
  • 1970-01-01
  • 2015-12-07
  • 2011-01-11
相关资源
最近更新 更多