簡體   English   中英

Rails 4-如何在postgres上存儲數組

[英]Rails 4 - How to store an array on postgres

我需要保存此數組:

params[:products]

該數組包含以下信息:

[{"'name'"=>"Product Name 1 ", "'id'"=>"2", "'quantity'"=>"2", "'accessory'"=>{"'id'"=>"8", "'name'"=>"Accessory Name 1"}}, {"'name'"=>"Product Name 2 ", "'id'"=>"5", "'quantity'"=>"1", "'accessory'"=>{"'id'"=>"40", "'name'"=>"Accessory Name 2"}}]

如您所見, accessory是另一個陣列。

過程是這樣的:一個前端人員為我提供了該數組,因此我想將所有數據存儲在order.rb模型中。

因此,我有幾個問題:

  • 我需要在數據庫上有“數組類型字段”嗎?
  • 我需要哪些領域?

我正在尋找一些示例,並且已經在我的order模型上進行了嘗試:

serialize :product

order = Order.new
order.product = [:product]
order.save
order.product

我對這種方法也很滿意http : //api.rubyonrails.org/classes/ActiveRecord/Store.html

也許這是一個基本問題,但我真的不知道如何解決。 如您所見,我在任何控制器中都沒有代碼,因為我真的不知道需要編寫什么。

謝謝您的幫助。

除了hstore之外,另一個解決方案是JSON,特別是我建議您使用PostgreSQL類型的“ jsonb”,因為它效率更高,請參閱文檔:

有兩種JSON數據類型:json和jsonb。 他們接受幾乎相同的值集作為輸入。 實際的主要區別是效率之一。 json數據類型存儲輸入文本的精確副本,處理函數必須在每次執行時重新解析; jsonb數據以分解后的二進制格式存儲,由於增加了轉換開銷,因此輸入速度稍慢,但由於不需要解析,因此處理速度明顯更快。 jsonb還支持索引編制,這可能是一個很大的優勢。

(更多信息在這里https://www.postgresql.org/docs/current/static/datatype-json.html

因此,與hstore相似,您可以執行一個查詢所依據的數據結構,並且該查詢非常快,如您在上面所讀。 與其他策略相比,這是一個顯着的優勢,例如序列化Ruby哈希並將其直接保存在數據庫中。

查爾斯

我建議您考慮使用Postgres的hstore類型。 使用它幾乎沒有好處(性能,對象索引等)。

enable_extension 'hstore'

這實際上使您的PSQL具有此支持。

您的遷移將如下所示:

class AddRecommendationsToPages < ActiveRecord::Migration
  def change
    add_column :pages, :recommendations, :hstore
  end
end

之后,您可以將所需的任何內容傳遞到hstore。

irb(main):020:0> Page.last.recommendations
  Page Load (0.8ms)  SELECT  "pages".* FROM "pages"  ORDER BY "pages"."id" DESC LIMIT 1
=> {"products"=>"34,32"}
irb(main):021:0> Page
=> Page(id: integer, block: string, name: string, slug: string, title: string, h1: string, annotation: text, article: text, created_at: datetime, updated_at: datetime, position: integer, parent: integer, show: boolean, recommendations: hstore)
irb(main):022:0> Page.last.recommendations["products"]
  Page Load (0.6ms)  SELECT  "pages".* FROM "pages"  ORDER BY "pages"."id" DESC LIMIT 1
=> "34,32"
irb(main):023:0>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM