【问题标题】:URL parameter in the URL itself instead of after ? in RailsURL 本身而不是之后的 URL 参数?在 Rails 中
【发布时间】:2012-05-28 11:15:01
【问题描述】:

我在路线中有以下行:

match 'area/:area_id/stores', :to => "stores_directory#index", :as => "stores_directory"

我有一个表单,我可以在其中选择 area_id:

<%= form_tag stores_directory_path, :method=>:get do %>

<select id="area_id" name="area_id">
....
</select>

这会将 area_id 作为参数广告在 ? 之后。所以,我的问题是:如何将它添加到 areastores 之间?

【问题讨论】:

    标签: ruby-on-rails-3 forms routes url-parameters


    【解决方案1】:

    我看到了一种解决方案(也许不是最好的,但也完全可以接受)。可以编写自己的中间件来处理这个请求,但我认为这是错误的方式(在这种情况下)。

    改为使用 JS 重定向

    这可以写成一个方法(使用 JQuery 的例子):

    $('#area_id option').click(function() {
      if (this.value) { // check value is not empty
        document.location.href = Routes.stores_directory_path({area_id: this.value})
      }
    });
    

    或者使用 options_for_select:

    options = []
    areas.each do |a|
      options << [a.to_s, a.id, {:onclick => "document.location.href = Routes.stores_directory_path({area_id: #{a.id}})"}]
    end
    options_for_select(options)
    

    这里我使用js-routes gem 来获得漂亮的网址。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-10-11
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 2014-03-28
      • 2012-04-12
      • 1970-01-01
      相关资源
      最近更新 更多