簡體   English   中英

ActiveRecord查詢以查找給定鍵的JSON值數組

[英]ActiveRecord Query to find JSON Value Array for a given Key

在Rails 4中,我有一個帶有JSON類型列的表。 我有一個像這樣很好的方法

def self.that_match_property(key: "default", value: "default")
  where("properties ->> ? = ?", key, value)
end

所以對於Model.first.properties我得到{"name": "Bill", "user_id": "1"}我可以做到這一點。

Model.that_match_property(key: "name", value: "Bill") 

然后在json properties列中獲得鍵/值對上匹配的一條或多條記錄。

但是...假設我希望該值是ID數組。 所以我有...

user1.properties = {"name": "Bill", "user_id": "1"}
user2.properties = {"name": "Ted", "user_id": "2"}
user3.properties = {"name": "Rufus", "user_id": "3"}

現在我還有bill_and_ted_ids = ["1", "2"]

我希望能夠做到這一點:

Model.that_match_property(key: "user_id", value: bill_and_ted_ids)

但這是行不通的。 通常,我可以將ID數組傳遞給活動記錄查詢,並將其轉換為適當的sql。

在Rails中使用JSON數據類型執行上述操作的正確方法是什么?

也許這樣的事情會有所幫助:

def build_where_query_string_from_hash(hash)
  hash.collect do |k,v|
    if v.is_a?(Array)
      string = v.collect{|e| "(properties ->> '#{k}'='#{e}')"}.join(" OR ")
      "(#{string})"
    else
      "(properties ->> #'{k}'='#{v}')"
    end
  end.join(" AND ")
end

那么您可以傳遞: build_where_query_string_from_hash(user_id: [1,2], name: ["Bill", "Ted"])

返回:

((properties ->> 'user_id'='1') OR (properties ->> 'user_id'='2')) AND ((properties ->> 'name'='Bill') OR (properties ->> 'name'='Ted'))`

暫無
暫無

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

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