2012-04-01 75 views
3

假設我有用戶數據存儲陣列寵愛於字符串數據類型Rails的活動記錄查詢,系列化陣列

[ 
    #<User id: 1, name: "John", pets: "---\n- cat\n- dog\n- bunny\n- ''\n">, 
    #<User id: 2, name: "Pete", pets: "---\n- dog\n- bunny\n- ''\n">, 
    #<User id: 3, name: "Jack", pets: "---\n- cat\n- ''\n">, 
    #<User id: 4, name: "Kurt", pets: "---\n- cat\n- bunny\n- ''\n"> 
] 

我能得到的是有一隻貓的所有用戶?也許像User.find_all_by...User.where(....)或返回作爲關係的東西?所以我可以訂購積極的記錄查詢。

我知道我能得到具有貓的所有用戶

User.all.select{|s| YAML.load(s.pets).include?'cat'} 

,但它轉換成數組,不能主動記錄查詢訂購。

thx幫助。

+0

檢查本文 http://stackoverflow.com/questions/9814622/searching-serialized-data-using-active-record – hiphapis 2015-04-28 07:46:25

回答

1

您需要規範化數據,添加寵物模型並設置這些模型之間的has_and_belongs_to_many關聯。

+0

出於某種原因,我避免再添加一種模型。如果沒有更好的解決方案,對我來說沒問題。 thx – raymondralibi 2012-04-01 08:54:21

3

您可以使用簡單的SQL來查看'cat'是否出現在序列化列中。

User.where('pets LIKE "%cat%"').all

+2

它也將檢索「鮎魚」 – raymondralibi 2012-04-01 09:14:51

+0

好點 - 然後做User.where('寵物LIKE「%cat \\ n%」')。all – frontendbeauty 2012-04-01 09:28:09