2. Routing - 2.3 Route Globbing

2.3 Route Globbing

# /items/list/base/books/fiction/dickens
get 'items/list/*specs', controller: 'items', action: 'list'

def list
  specs = params[:specs] # e.g, "base/books/fiction/dickens"
end

# http://localhost:3000/items/q/field1/value1/field2/value2/...
get 'items/q/*specs', controller: "items", action: "query"

def query
  @items = Item.where(Hash[params[:specs].split("/")]) 
  if @items.empty?
    flash[:error] = "Can't find items with those properties" 
  end
  render :index 
end

Hash converts a one-dimensional arrayof key/value pairs into a hash! Further proof that in-depth knowledge of Ruby is a prerequisitefor becoming an expert Rails developer.

你可能感兴趣的:(2. Routing - 2.3 Route Globbing)