[英]Rails ActiveRecord nested .create! with PSQL POINT type
我正在嘗試使用 Rails 和 ActiveRecord 創建一個深度嵌套的 object。
Order.create!(params)
model 包含一個子Address
,該地址具有 PSQL 類型 POINT 的coordinates
字段。
因此,當我嘗試創建它時,出現以下錯誤。 我猜它試圖通過使用提供的字段首先加載Address
類型,但因為沒有=
比較而掛斷在coordinates
(POINT) 類型上(根據https://www.postgresql ,它是作為~=
完成的。 org/docs/13/functions-geometry.html )。
所以我的問題......有沒有辦法向 ActiveRecord 提供提示以幫助它正確執行此查詢,或者我應該如何解決這個問題?
Address Load (0.7ms) SELECT "addresses".* FROM "addresses" WHERE "addresses"."firstname" = '-' AND "addresses"."lastname" = '-' AND "addresses"."phone" = '-' AND "addresses"."coordinates" = '-74.0064172,40.7049028' AND "addresses"."address1" = '110 Wall St' AND "addresses"."address2" = '' AND "addresses"."city" = 'New York' AND "addresses"."zipcode" = '10005' AND "addresses"."state_id" = 1 AND "addresses"."country_id" = 1 LIMIT 1
↳ app/services/cart/create_cart_service_decorator.rb:21:in `call'
PG::UndefinedFunction: ERROR: operator does not exist: point = unknown
LINE 1: ..."phone" = '-' AND "addresses"."coordinates" = '-74.006...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
這是一個獨立的文件來重現這一點。
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem "activerecord", "6.1.3.2"
gem "pg"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "postgresql", database: "test-db")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :addresses, force: true do |t|
t.point :coordinates
end
end
class Address < ActiveRecord::Base
end
class BugTest < Minitest::Test
def test_nested_saving
address = Address.find_or_create_by!({ coordinates: ActiveRecord::Point.new(0, 0) })
assert address
end
end
您需要將參數顯式類型轉換為 ActiveRecord::Point 實例,從某些版本開始就支持該實例:
x, y = params[:coordinates].split(',').map(&:to_f)
params[:coordinates] = ActiveRecord::Point.new(x, y)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.