2011-12-19 90 views
0

至少,我認爲這就是問題的原因...... 我試圖創建一個頁面,通過查詢字符串發送子字符串,並且顯示與子字符串匹配的給定數組的成員在頁面上。我知道邏輯在我的模型作品中,但顯然有些東西是不正確的,因爲當我發送匹配數組的幾個成員的子字符串時,它會返回「無匹配」。我很確定問題出在模型或遷移的某個地方。問題實施模型

這裏的模型:

class State < ActiveRecord::Base 
def State.filter(matching_string) 

    matcher = Regexp.new(matching_string, Regexp::IGNORECASE) 
    @new_array = [] 
    State.select{|x| if matcher =~ x then @new_array << x end} 
    return @new_array 

end 
end 

這裏的遷移:

class CreateStates < ActiveRecord::Migration 


def self.up 

    list_of_states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", 
    "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", 
    "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", 
    "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", 
    "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", 
    "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", 
    "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", 
    "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", 
    "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", 
    "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"] 


    create_table :states do |t| 
     t.string :name 
     t.timestamps 
    end 
    State.reset_column_information 
    for x in list_of_states 
      State.create(:name => x) 

    end 
    State.all.collect {|x| x.name} 
    end 



    def self.down 
    drop_table :states 
    end 
end 

而這裏的控制器:

class StatesController < ApplicationController 
def filter 
    @states = State.filter(params[:substring]) 
    @entered_string = params[:substring] 
end end 

TIA!

+0

請提供'params [:substring]'sample – Bohdan 2011-12-19 15:28:17

+0

例如,url的結尾是?substring =「la」,顯然與阿拉巴馬州,阿拉斯加州和其他一些字符串相匹配,但我是仍然收到「不匹配」 – user1104967 2011-12-19 15:52:06

+0

作爲說明,您不應該在遷移中使用模型。在將來的某個時候,你甚至可能還沒有一個狀態模型,此時該遷移將無效並且不會運行。使用'execute'直接插入數據雖然更麻煩,但好得多。 – tadman 2011-12-19 16:27:46

回答

0

我認爲你遇到的問題是由於錯誤地使用了select方法。 ActiveRecord :: Base實現用於選擇特定的列。你將一個塊傳遞給一個不需要的方法,這樣它就會被忽略。最終的結果是什麼都沒有。

Ruby中有幾個約定會使這種不正當行爲更明顯,更易於修復。舉例來說,這是多麼如果按照紅寶石約定完成的方法將被寫入:

class State < ActiveRecord::Base 
    def self.filter(matching_string) 
    pattern = Regexp.new(matching_string, Regexp::IGNORECASE) 

    State.select{ |state| state.name.match(pattern) } 
    end 
end 

你會發現,這種方法的結果總是nil,這樣的東西是不對的。你真正想要的更多是這樣的:

class State < ActiveRecord::Base 
    def self.filter(matching_string) 
    pattern = Regexp.new(matching_string, Regexp::IGNORECASE) 

    @states ||= State.all 
    @states.select{ |state| state.name.match(pattern) } 
    end 
end 

這假定你不在應用程序重新啓動之間添加和刪除狀態。如果處理僅限美國的數據,這是一個相當安全的假設,特別是因爲您的數據通過遷移加載並且看起來不是用戶可編輯的。

使用LIKE運營商用戶也可以簡單地搜索數據庫:

class State < ActiveRecord::Base 
    def self.filter(matching_string) 
    State.where('name LIKE ?', "%#{matching_string}%") 
    end 
end 

第一種方法適用於國家的小型列表更好,後者爲大名單。在這種情況下,「大」意味着1000+。