Rails使用参数构造或重写URL

时间:2013-12-14 20:21:22

标签: ruby-on-rails url-rewriting routes

在我的根页面上,我有一个索引操作,列出了图像模型中的所有内容。

在索引操作中,您可以将3个过滤器应用于列表,该过滤器仅显示符合过滤条件的任何内容。选择选择框并单击过滤器时,这些参数会在URL中显示:

http://localhost:3000/gender=m&height=62&weight=130

我怎样才能这样做,URL将重写为:

http://localhost:3000/m/62/130/

这些值是图像模型中的属性,存储在性别,高度和重量列中。 或者,更好的是,重写为像这样的东西

http://localhost:3000/men/62-inches/130-lbs/

这是我尝试过的,把它放在路线中: 匹配“/:gender /:height /:weight”,:controller => “images”,:action => “index”,:conditions => {:method => :get},来自:'get'

模型:

class Image < ActiveRecord::Base

  validates :gender, :measure_type, presence: true

  validates :image_location, presence: true, uniqueness: true

  validates :weight, length: {maximum: 3}



  has_attached_file :photo, styles: {

  small: '240x300'

  }

end

my routes.rb:

Images::Application.routes.draw do

     # match "/:gender/:height/:weight", :controller => "images", :action => "index", :conditions => { :method => :get }

     get 'images', to: redirect('/')

     match 'upload' => 'images#new',  :as => 'new_image_path',   via: 'get'

     match '/upload', :to => 'images#create', :via => :post, :as => :post_upload

     root "images#index"
 end

index.html.erb

<h1>Images</h1>
  <%= form_tag root_path, method: :get do %>

  <%= select_tag "gender", options_for_select(["m", "w"], params[:gender]) %>

  <%= select_tag "height", options_for_select((60..70).to_a.map{|s| ["#{s} inches", s]}, selected: params[:height]), :prompt => "all" %>

  <%= select_tag "weight", options_for_select((100..300).step(5).to_a.map{|s| ["#{s} lbs", s]}, selected: params[:weight]), :prompt => "all" %>  

  <%= submit_tag 'Filter', name: nil %>

<% end %>

<table>

  <tr>

    <th>Gender</th>

    <th>Height</th>

    <th>Weight</th>

    <th>Image location</th>

  </tr>

<% @images.each do |image| %>

  <tr>

    <td><%= image.gender %></td>

    <td><%= image.height %></td>

    <td><%= image.weight %></td>

    <td><%= image.image_location %></td>


  </tr>

<% end %>

</table>

images_controller.rb

class ImagesController < ApplicationController

   def index

     @images= Image.where(gender: params[:gender], height: params[:height], 

                                    weight: params[:weight])
   end
end

更新1:

我开始认为它可能涉及在路线中做一些事情,比如get'/',to:redirect('/ params [gender] / params [height] / params [weight]')

更新2:

我想我已经解决了这个问题,经过几个小时的搜索后找到了答案 - Ruby on Rails: How to redirect page based on post params in search_field?

1 个答案:

答案 0 :(得分:0)

使图像路径定义像这样

resources :images do    
  get "(gender/:gender)(/height/:height)(/weight/:weight)", :action => :index, :on => :collection
end