#111 Advanced Search Form

If you need to create an advanced search with a lot of fields, it may not be ideal to use a GET request as I showed in episode 37. In this episode I will show you how to handle this by creating a Search resource.
<!-- views/searches/new.html.erb -->
<% form_for @search do |f| %>
<p>
<%= f.label :keywords %><br />
<%= f.text_field :keywords %>
</p>
<p>
<%= f.label :category_id %><br />
<%= f.collection_select :category_id, Category.all, :id, :name, :include_blank => true %>
</p>
<p>
Price Range<br />
<%= f.text_field :minimum_price, :size => 7 %> -
<%= f.text_field :maximum_price, :size => 7 %>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>

# models/search.rb
def products
@products ||= find_products
end

private

def find_products
Product.find(:all, :conditions => conditions)
end

def keyword_conditions
["products.name LIKE ?", "%#{keywords}%"] unless keywords.blank?
end

def minimum_price_conditions
["products.price >= ?", minimum_price] unless minimum_price.blank?
end

def maximum_price_conditions
["products.price <= ?", maximum_price] unless maximum_price.blank?
end

def category_conditions
["products.category_id = ?", category_id] unless category_id.blank?
end

def conditions
[conditions_clauses.join(' AND '), *conditions_options]
end

def conditions_clauses
conditions_parts.map { |condition| condition.first }
end

def conditions_options
conditions_parts.map { |condition| condition[1..-1] }.flatten
end

def conditions_parts
private_methods(false).grep(/_conditions$/).map { |m| send(m) }.compact
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值