我有一個名爲「image」的模型,我需要找到所有圖像,但圖像名稱屬性中包含表達式「User」的圖像除外。在Rails 4中查找帶有排除項的所有條目
Image.rb:
class Image < ActiveRecord::Base
attr_accessible :name
end
所以,它應該是這樣的:
@images = Image.where( 「!NAME =〜 '/用戶/我'」)
正確的術語是什麼?
我有一個名爲「image」的模型,我需要找到所有圖像,但圖像名稱屬性中包含表達式「User」的圖像除外。在Rails 4中查找帶有排除項的所有條目
Image.rb:
class Image < ActiveRecord::Base
attr_accessible :name
end
所以,它應該是這樣的:
@images = Image.where( 「!NAME =〜 '/用戶/我'」)
正確的術語是什麼?
的PostgreSQL在Rails 4中:
Image.where.not("name ~ ?", "User")
MySQL in Rails 4:
Image.where.not("name RLIKE ?", "User")
來源:http://viget.com/extend/regular-expressions-in-mysql – 2014-01-21 18:18:55
@images = Image.where.not(name: user)
或者,如果 「用戶」 是字符串:
@images = Image.where.not(name: "user")
好的,但它應該是一個REGEXP,所以:name不應該包含單詞「user」。例如。 「第一個用戶」應該是一個結果... – user929062
嘗試這個
@images = Image.where.not( 「name = '用戶'」)
我也在下面添加了commoon:它應該是一個REGEXP,所以::name不應該包含單詞「user」。例如。 「第一個用戶」不應該是一個結果......你的表達式排除了所有的圖像,其中:name =='user'我猜。 – user929062
如果使用squeel
寶石(https://github.com/activerecord-hackery/squeel),那麼你可以這樣做:
exclusion_value = "user"
Image.where{name !~ exclusion_value}
通常你不會在SQL中使用正則表達式,肯定在你的情況有沒有必要。一個簡單的'NOT LIKE'子句就足夠了。 – thomasfedb