gpt4 book ai didi

ruby-on-rails - postgres_ext/serializers 帮助...看起来很简单,但无法按照描述进行任何操作

转载 作者:行者123 更新时间:2023-12-01 17:30:09 25 4
gpt4 key购买 nike

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

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

我使用的是 Rails 4.2.3 和 Ruby 2.2

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

require 'postgres_ext/serializers'

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

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

Just require 'postgres_ext/serializers' and use ActiveModel::Serializers as you normally would!

因此,我将 require 'postgres_ext/serializers' 添加到我的 application.rb 中,对序列化器进行了一些小编辑以查看它是否有效:

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

谢谢!

最佳答案

您是否尝试过将此 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

来自文档:

... call by looking for a class method with the same name and the suffix __sql ...

关于ruby-on-rails - postgres_ext/serializers 帮助...看起来很简单,但无法按照描述进行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31827932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com