簡體   English   中英

如何實現等效的model.where {| m | m.arr.include? X }

[英]How to implement equivalent of model.where { |m| m.arr.include? x }

因此,我意識到Rails不支持將塊傳遞給模型上的函數。 我應該如何檢索具有包含某些給定元素的數組屬性的所有對象?

where方法的目的是向ActiveRecord生成的SQL查詢中添加WHERE子句-它不對結果執行任何過濾:

Post.                        # initializes query:  SELECT * FROM `posts`
  where(author_id: 42).      # adds:  WHERE `posts`.`author_id` = 42
  to_a                       # <-- it's only here that the query is executed

如果必須使用塊篩選結果集,你必須執行查詢來獲得一個數組的結果,然后用select法來篩選數組:

Post.all.                            # SELECT * FROM `posts`
  to_a.                              # <-- executes query, returns the results in an array
  select { |p| p.arr.include?(x) }   # filter array

顯然,如果您有很多記錄,這將非常慢 ,因為您的應用程序必須從數據庫中獲取每條記錄,對它們的數組屬性進行反序列化,並為過濾條件檢查每條記錄。


文檔鏈接:

暫無
暫無

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

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