2014-01-21 44 views
0

我有一個名爲「image」的模型,我需要找到所有圖像,但圖像名稱屬性中包含表達式「User」的圖像除外。在Rails 4中查找帶有排除項的所有條目

Image.rb:

class Image < ActiveRecord::Base 
    attr_accessible :name 
end 

所以,它應該是這樣的:

@images = Image.where( 「!NAME =〜 '/用戶/我'」)

正確的術語是什麼?

+0

通常你不會在SQL中使用正則表達式,肯定在你的情況有沒有必要。一個簡單的'NOT LIKE'子句就足夠了。 – thomasfedb

回答

1

的PostgreSQL在Rails 4中:

Image.where.not("name ~ ?", "User") 

MySQL in Rails 4:

Image.where.not("name RLIKE ?", "User") 
+0

來源:http://viget.com/extend/regular-expressions-in-mysql – 2014-01-21 18:18:55

0
@images = Image.where.not(name: user) 

或者,如果 「用戶」 是字符串:

@images = Image.where.not(name: "user") 
+0

好的,但它應該是一個REGEXP,所以:name不應該包含單詞「user」。例如。 「第一個用戶」應該是一個結果... – user929062

0

嘗試這個

@images = Image.where.not( 「name = '用戶'」)

+0

我也在下面添加了commoon:它應該是一個REGEXP,所以::name不應該包含單詞「user」。例如。 「第一個用戶」不應該是一個結果......你的表達式排除了所有的圖像,其中:name =='user'我猜。 – user929062

相關問題