我还在学习RoR,它花了我一整天的时间来找出一个简单的搜索字段,按照卧室的数量过滤属性。它现在工作得很好,但我不知道它是否是正确的方法,因为我无法弄清楚如何调整它,以便我可以为浴室添加额外的搜索字段,最低价格,最高价格,拉链等。< / p>
搜索字段和提交按钮以及结果在列表页面上,所以在控制器中我有:
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
答案 0 :(得分: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