2012-05-20 113 views
0

我仍然在學習RoR,並且我整天都在弄清楚一個簡單的搜索字段,可以根據臥室數量過濾屬性。它的工作現在完美了,但我不知道它是否是正確的方式來做到這一點,因爲我無法弄清楚如何調整它,這樣我就可以爲浴室添加額外的搜索字段,最低價格,最高價格,拉鍊等。導軌中的多個搜索字段

搜索字段和提交按鈕,結果列表頁面上,以便在控制器我有:

def list 
@properties = Property.bedrooms(params[:bedrooms]) 
end 
模型

我:

def self.bedrooms(bedrooms) 
if bedrooms 
    find(:all, :conditions => ["bedrooms LIKE ?", "%#{bedrooms}%"]) 
else 
    find(:all) 
end 

和list.html.erb頁:

<%= form_tag('list', :method => 'get') do %> 
<p> 
<%= text_field_tag 'bedrooms', (params[:bedrooms]) %> 

<%= submit_tag "Search", :name => nil %> 
</p> 
<% end %> 

如何添加一個搜索欄浴室,另一個是最低價格,另一個是最大的價格,另一個用於拉鍊等?謝謝,亞當

我得到的語法錯誤時,試圖將它添加到控制器:

scope :bedrooms, {|b| where("bedrooms LIKE ?", b)} 
scope :price_greater, {|p| where("price > ?", p)} 

錯誤是:

SyntaxError in PropertiesController#list 

/Users/Adam/Documents/Websites/idx_app/app/models/property.rb:4: syntax error, unexpected '|', expecting '}' 
scope :bedrooms, {|b| where("bedrooms LIKE ?", b)} 
       ^
/Users/Adam/Documents/Websites/idx_app/app/models/property.rb:4: syntax error, unexpected '}', expecting keyword_end 
scope :bedrooms, {|b| where("bedrooms LIKE ?", b)} 
               ^
/Users/Adam/Documents/Websites/idx_app/app/models/property.rb:5: syntax error, unexpected '|', expecting '}' 
scope :price_greater, {|p| where("price > ?", p)} 
        ^
/Users/Adam/Documents/Websites/idx_app/app/models/property.rb:5: syntax error, unexpected '}', expecting keyword_end 

是添加lambda表達式固定在上面的語法錯誤,但現在它好像@properties不返回數組,因爲我收到以下錯誤消息:

undefined method `each' for #<Class:0x007fd5235250f8> 

Extracted source (around line #29): 

26:  <th>Price</th> 
27:  
28:  </tr> 
29:  <% @properties.each do |property| %> 
30:  <tr> 
31:  
32:  <td><%= link_to(property.address, {:action => 'show', :id => property.id}) %></td> 

修正此錯誤消息,我沒有在控制器正確定義它,我已經把@ properties.all代替@properties = @ properties.all

回答

2

使用範圍做...

scope :bedrooms, lambda{ |b| where("bedrooms LIKE ?", b) }  
    scope :price_greater, lambda{ |p| where("price > ?", p) } 

在控制器

@properties = Property.scoped 
    @properties = @properties.bedrooms(params[:bedrooms]) if params[:bedrooms].present? 
    @properties = @properties.price_greater(params[:min]) if params[:min].present? 
    ..... 
    @properties = @properties.paginate.... or just @properties.all 
+0

正確的我明白了,不知道你可以繼續重新定義它的下一行@properties和增加更多的條件吧,以後會盡量讓你知道,非常感謝您的回答 – railsy

+0

見以上爲我得到的錯誤 – railsy

+0

sry,修正)忘了添加逗號和lambdas –