2016-08-08 41 views
0

因此,我有一個product模型,其文本屬性爲換行符tags。這背後的原因是,有一個每天運行的查詢遍歷每個這些字段按照產品構建正則表達式,我希望它儘可能快。這些產品每幾個月只能添加或更新一次,因此驗證並不需要那麼高效,但我希望能夠像以前的限制一樣好。高效驗證文本字段元素的唯一性

到目前爲止,我想出的是這樣的:

def build_regex_string 
    '(' + tags.gsub(/(\r?\n(?!$))/,'|').gsub(/(\r?\n)/,'') + ')' 
end 

def validate_tags_are_unique 
    Product.where.not(id: id).each do |product| 
    tags_regex = Regexp.new(product.build_regex_string) 
    return false if tags_regex.match(tags) 
    end 
end 

我使用正則表達式主要是因爲它是一種方法,我已經有了。我試圖研究將驗證直接寫入pSQL中的遷移是否會更好?我對此不甚瞭解。我研究的另一件事是使用數組類型,但我沒有找到一個ActiveRecord驗證,它可以完成我想要的數組,並且我不想浪費時間構建和重建數組。最後,我考慮了將正則表達式實際存儲在數據庫中的方法,但看起來像是我必須從字符串中構建正則表達式。

+1

您需要優化的當前代碼有多慢? –

回答

0

你爲什麼不用Ruby來做這件事? Ruby中非常簡單。

def validate_tags_are_unique 
    self_tags = tags.split(/\n/) 
    Product.where.not(id: id).tags.all?{ |t| (self_tags - t.split(/\n/)).empty? } 
end 
+0

它將無法正常工作,因爲Product.where.not(id:id)返回沒有標籤屬性的集合。 – SunnyMagadan

+0

Product.where.not(id:id).all? {| prod | (self_tags&prod.tags.split(/ \ n /))。empty? }更正確(所有產品沒有使用當前產品標籤的通用標籤) – SunnyMagadan

+0

我修復了它。謝謝! – Nathan