![](/img/trans.png)
[英]Ruby: Compare 2 arrays for matches, and count the number of match instances
[英]Grouping a set of instances that almost match in Ruby
我有一組屬性要像這樣在控制器中抓取-
def index
@properties = Property.all
@properties = @properties.where("bedrooms = ?", params[:bedrooms]) if params[:bedrooms].present?
@properties = @properties.text_search(params[:query]) if params[:query].present?
@properties = @properties.area_search(params[:area]) if params[:area].present?
@properties = @properties.where("month_available = ?", params[:availability]) if params[:availability].present?
@properties = @properties.where("vacancy_status = ?", params[:now]) if params[:now].present?
end
我正在通過渲染局部視圖來顯示它們,這是我的問題-
該視圖包含滿足以上搜索條件的所有屬性,有時是100多個屬性。 這些屬性中的某些屬性具有幾乎相同的地址,因為它們位於同一建築物中,但是具有不同的單元號,但是不幸的是,該單元號附加到了我的數據庫(例如123 Main Street B)中的:street_address屬性。 在顯示搜索結果時,我只需要顯示一次該地址(例如123 Main Street),而不是顯示該地址的每個實例(最多可以顯示40次)。 我必須繼續顯示滿足搜索條件的所有其他屬性,這並不是好像我只是在提取單個地址的數據一樣。 通常情況下,我會提取具有4個卧室或類似房屋的所有屬性的數據。
旁注:我正在使用從數據庫中提取的400多個屬性來執行此操作,因此我無法在地址中進行硬編碼,我需要動態的解決方案,這一直是我進入數據庫的關鍵解。 在此先感謝您的幫助或指導。
給這個例子一個鏡頭:(我按地址分組,除了最后一個字符,然后剝離。您可以根據對屬性列出方式的了解來增強分組)
addresses = ["123 main st. A", "123 main st. J", "124 Main street", "123 main st."]
# define how properties are grouped here; don't worry about "weird" groups; they'll only contain one value and we'll get rid of it in the next line
map = addresses.group_by { |a| a[0..-2].strip }
(addresses - map.reject { |k,v| v.length < 2 }.values.flatten).collect { |k| { k => map[k] || k } }
=> [{"124 Main street"=>"124 Main street"},
{"123 main st."=>["123 main st. A", "123 main st. J"]}]
如果只是與地址字符串開頭匹配的簡單文本,則可以使用SQL LIKE :
@properties.where("address LIKE ?", "#{params[:address]}%")
在這里,我使用%
通配符來告訴它SQL將地址與其后的任何內容匹配,因此:
"123 Main St" will match "123 Main St and anything here"
希望能有所幫助。
如果只想顯示一次屬性,則有一個簡單的方法。 如何采用前7個(或任何您需要的字符)字符。 這樣,門牌號碼+街道地址的一部分會匹配,並且您僅使用該匹配的第一個數據庫匹配。 您還可以獲取所有結果,獲取前7個字符,然后將其放入數組並進行處理。
當添加到數組中時,只需執行以下操作:
myarray = myarray.uniq
現在您每個地址都有一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.