2014-02-17 22 views
0

我已經經歷過來自用戶的形式發送參數縮小的Properties數量在@properties哈希內匹配,現在這裏的問題 -只顯示一個紅寶石散列的一個實例,如果某些參數的前8個字符

數據庫中有許多屬性具有相似的街道地址(最多8個字符),我想只顯示其中一個屬性,在我看來而不是5或7或14.下面的代碼是我如何努力實現這一目標,但似乎並不奏效。任何指導將不勝感激。

這裏是在控制器中的索引操作 -

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(Date.today.mon <= :month_available <= Date.today.mon + 2) if params[:now].present? 
    @properties = @properties.page(params[:page]).per(30) 
end 

這裏的視圖(視圖/屬性/ index.html.erb) -

<% @properties.uniq {|p| [p.latitude, p.longitude, p.street_address[0..7]]}.each do |property| %> 
    <%= render "property", :property => property %> 
<% end %> 

這裏是爲架構數據庫中的表 -

create_table "properties", force: true do |t| 
    t.string "street_address" 
    t.string "city" 
    t.string "zipcode" 
    t.string "short_description" 
    t.text  "long_description" 
    t.integer "rent" 
    t.string "application_fee" 
    t.string "bedrooms" 
    t.string "bathrooms" 
    t.string "vacancy_status" 
    t.string "month_available" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "latitude" 
    t.string "longitude" 
    t.string "images",   default: [], array: true 
    t.string "amenities",   default: [], array: true 
    t.string "year_ready" 
end 
+0

這些特性都具有相同的緯度和經度? – coreyward

+0

@coreyward - 是的,他們實際上是單個建築物內的單個單位。所有位於同一建築物內的單位在數據庫中列出了相同的緯度和經度座標。 –

+0

該代碼有什麼問題? – mdesantis

回答

2

如果@propertiesActiveRecord::Relation,那麼uniq方法與核心Ruby中的Array#uniq方法不一樣。在活動中記錄distinct methoduniq method is an alias,它不會對傳遞的塊執行任何操作。由於在Ruby中你可以將一個塊傳遞給任何方法,因此它被有效地忽略。

您可以將結果轉換成數組to_a,然後使用上,該Array#uniq方法:

@properties.to_a.uniq {|p| [p.latitude, p.longitude, p.street_address[0..7]]}.each do |property| 
    # as before ... 
+0

非常感謝,不僅僅是爲了答案,還有關於Ruby的更多信息和閱讀材料。總是感激更多的教育努力。 –

相關問題