我已經建立了從瑞安貝特的鐵軌一個簡單的搜索轉換:在搜索結果中顯示 http://railscasts.com/episodes/37-simple-search-formRuby on Rails的簡單的搜索和範圍過濾器
後,我想有一個可以進行排序已經搜查了幾個環節信息。對於我的產品模型,他們按名稱搜索並獲得結果。我希望在搜索下有類別鏈接,以便他們可以按類別過濾搜索結果。 控制器是直截了當:
def index
@products = Product.search(params[:search])
#scope filtering
if params[:toys]
@products = Product.toys
end
end
我已經加入模型中的範圍,但我不知道如何將SQL語句的範圍和搜索結合起來。
class Product < ActiveRecord::Base
scope :electronics, -> { where(category: 'electronics') }
scope :toys, -> { where(category: 'toys') }
def self.search(term)
where("name like :term", term: "%#{term}%")
end
end
和視圖:index.html.erb
<%= form_tag products_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<%= link_to 'Electronics', products_path(:electonrics => true) %> | <%= link_to 'Toys', products_path(:toy => true) %>
基本上當我搜索的形式進入到localhost:3000/UTF8產品✓=搜索& = foo的 得到所有的結果嗎? foo,因爲它應該。然後,當我點擊過濾器搜索我需要某種形式的加入或工會進行搜索本地主機後唯一的電子:3000/UTF8產品✓=搜索& = foo的&類別=玩具。
如果在用戶搜索某個字段後,有一種更簡單的按類別排序的方法,我確信我和其他人在rails上學習ruby會感到非常高興,看到更加有效的方法來解決問題。現在你在做@products = Product.toys
重置列表
def index
@products = Product.all
@products = Product.search(params[:search]) unless params[:search].blank?
@products = @products.toys unless params[:toys].blank?
end
: