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

是的,添加 lambdas 修复了上述语法错误,但现在好像 @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

4

1 回答 1

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
于 2012-05-20T01:25:06.360 回答