Jul*_*ius 2 ruby postgresql ruby-on-rails
无法处理数组过滤。这个:
@profiles = Profile.filter(params.slice(:location, :status, :items))
Run Code Online (Sandbox Code Playgroud)
传递要过滤的记录:
def filter(filtering_params)
results = self.where(nil)
puts filtering_params
filtering_params.each do |key, value|
if value.is_a?(Array)
results = results.public_send(key, value.to_s) if self.where("#{key}", value)
else
results = results.public_send(key, value) if value.present?
end
end
results
end
Run Code Online (Sandbox Code Playgroud)
但是 Postgres 数组存在一些问题。传递给filter方法的参数是:
参数:{"utf8"=>"?", "location"=>"0", "status"=>"0", "items"=>["0", "1"], "commit"=> "过滤器"}
和方法接收它们:
{“位置”=>“0”,“状态”=>“0”,“物品”=>[“0”,“1”]}
但我得到错误:
PG::InvalidTextRepresentation: 错误: 格式错误的数组文字: "0" LINE 1: ..." = $2 AND "profiles"."items" IN ('0', '1') ... ^
详细信息:数组值必须以“{”或维度信息开头。: SELECT "profiles".* FROM "profiles" WHERE "profiles"."location" = $1 AND "profiles"."status" = $2 AND "profiles"."items" IN ('0', '1') LIMIT 3 美元抵消 4 美元
这个错误实际上指向了我想要显示接收到的记录的位置:
<% rofiles.each do |profile| %>
这个 Postgres 数组发生了什么..?
gem 'rails', '~> 5.0.3'
gem 'pg', '~> 0.18'
Run Code Online (Sandbox Code Playgroud)
编辑:
看起来 t 现在适用于范围:
scope :items, -> (items) { where "items && ARRAY[?]::integer[]", items }
Run Code Online (Sandbox Code Playgroud)
和:
def filter(filtering_params)
results = self.where(nil)
filtering_params.each do |key, value|
puts value
if value.is_a?(Array)
value = [0, 1, 2]
results = results.public_send(key, value) if self.where("key && ARRAY[?]::integer[]", value)
else
results = results.public_send(key, value) if value.present?
end
end
results
end
Run Code Online (Sandbox Code Playgroud)
ActiveRecord 不会自动为数组类型列创建查询。
查询数组列可以通过以下方式完成:
Profile.where("items@> ARRAY[?]::varchar[]", ["0", "1"])
# or
Profile.where("items@> ARRAY[?]::integer[]", [0, 1])
Run Code Online (Sandbox Code Playgroud)
但是如果 items 是您应用程序中的模型,您应该创建一个连接表。数组不能替代关系数据建模。
| 归档时间: |
|
| 查看次数: |
2382 次 |
| 最近记录: |