還不如寫自己的邏輯,這一點,因爲我不認爲做一個插件是要提出自己:
我假設城市和國家有ID。如果沒有,邏輯實際上會更簡單。 使用jQueryUI的自動完成爲您的元素觸發自動完成。添加一個控制器方法,該方法會將您的城市和國家/地區標籤(可能是城市對象上的方法)與您的ID一起作爲json。在自動填充「選擇」回調中,爲城市和國家ID在表單中設置隱藏字段。這最後一部分是可選的,因爲我不知道你打算如何從表單中保存這些數據。
下面的例子假設你的應用很多,但應該足以讓你開始:
的視圖腳本的
例如:
$("#yourField").autocomplete({
source: "/path_to_your_action",
minLength: 2,
select: function(event, ui) {
$(this).val(ui.item.label);
$(this).find("#country_id").val(ui.item.country_id);
$(this).find("#city_id").val(ui.item.city_id);
event.preventDefault;
}
})
控制器:
def your_action
term = params[:term]
cities = City.where("cities.name like ?", "%#{term}%")
.limit(25)
.all
render :json=>cities.collect{|c| {:label=>c.your_label_method, :city_id=>c.id, :country_id=>c.country_id}}
end
city.rb
def your_label_method
"#{self.name}, #{self.country.name)}"
end
有一個很好的方式在這個正確的方向,thx! – Rubytastic 2012-02-03 15:42:20