2010-01-07 53 views
0

好了,可能是最好的,如果我只是粘貼代碼,然後解釋插入可變進查找條件=> SQL查詢

search = "your horses" 

    exp1 = "" 
    exp2 = "" 

    myarray = search.split(/ /) 
    mylength = myarray.length   #this would return 2 in this case 

    mylength.times do 
    exp1 += "AND name LIKE ? "   #this gives--> AND name LIKE ? AND name LIKE ? 
    end 

    for i in 0..(mylength - 1) 
    exp2 += ("%#{myarray[i]}%, ") #and this gives--> your, horses, 
    end 

find(:all, :conditions => ["#{exp1}", exp2]) 

,並在這裏結束我碰到一個問題,因爲EXP2變成了「你的馬,」在find函數中。在這些條件下我必須做什麼,不會有插入額外的單引號標記?

或者我應該採取其他方式?

非常感謝您的回答!

回答

2
search = "your horses" 
    myarray = search.split(/ /) 
    mylength = myarray.length  
    find(:all, :conditions => [myarray.map{|x| 'name like ?'}.join(' AND '), *(myarray.map{|x| "%#{x}%"})]) 
+0

真誠地再次感謝你 – user235195 2010-01-07 23:20:28

0

我不知道如何用Ruby編譯逗號分隔值時寫這篇文章,但作爲一般規則,我發現最容易把逗號在開始時要附加像這樣:

var = ''; 

var += ',name1'; 
var += ',name2'; 
var += ',name3'; 

print substring(var, 1); 

這對我來說一直比較容易,而不是試圖檢測額外的逗號並將其從最後切掉。希望Ruby中有一個子字符串命令。 :)

1

嘗試刪除你的最後for塊,做這個: 「?」

find(:all, :conditions => [exp1, *exp2]) 

這應該把你的替換爲數組的最後一個元素,這是正確的Rails語法。

(另外,不知道爲什麼你通過插值本身轉化EXP1,字符串轉換爲字符串 - "#{expr1}"相同expr1.

1

我用匯編一組條件的技術增量再餵養通過對查找調用多次的它尤其適用於這樣的事情:

search = "your horses" 

# Establish a template conditions set 
conditions = [ [ ] ] 

# For each part of the name, add an element 
# to the conditions. 
search.split(/\s+/).each do |name| 
    conditions[0] << 'name LIKE ?' 
    conditions << "%#{name}%" 
end 

# Collapse the array into a single string 
conditions[0] = conditions[0].join(' AND ') 

# Run the query 
find(:all, :conditions => conditions) 

,關鍵是要開始與一個單一的空數組空數組。將WHERE條件附加到第一個元素,並將佔位符附加到整體條件Array。

這很靈活,您可以根據需要選擇使用OR或AND,當使用命名範圍進行擴充時,可以做更多的事情。

0

我知道這已經回答了,但你正在尋找一個名字上的幾個字,不是嗎?

在這種情況下,我認爲你可以用一個 LIKE條件做SQL查詢。換句話說:

search = "your horses" 
searchWithPercents = "%#{search.split.join('%')}%" # --> '%your%horses%' 
find(:all, :conditions => ['name LIKE ?', searchWithPercents]) 

無需創建一個複雜的查詢與ANDS