至少,我認爲這就是問題的原因...... 我試圖創建一個頁面,通過查詢字符串發送子字符串,並且顯示與子字符串匹配的給定數組的成員在頁面上。我知道邏輯在我的模型作品中,但顯然有些東西是不正確的,因爲當我發送匹配數組的幾個成員的子字符串時,它會返回「無匹配」。我很確定問題出在模型或遷移的某個地方。問題實施模型
這裏的模型:
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!
請提供'params [:substring]'sample – Bohdan 2011-12-19 15:28:17
例如,url的結尾是?substring =「la」,顯然與阿拉巴馬州,阿拉斯加州和其他一些字符串相匹配,但我是仍然收到「不匹配」 – user1104967 2011-12-19 15:52:06
作爲說明,您不應該在遷移中使用模型。在將來的某個時候,你甚至可能還沒有一個狀態模型,此時該遷移將無效並且不會運行。使用'execute'直接插入數據雖然更麻煩,但好得多。 – tadman 2011-12-19 16:27:46