【问题标题】:rails routes access by resource name using friendly_id gemrails 使用 friendly_id gem 按资源名称路由访问
【发布时间】:2012-02-11 13:36:21
【问题描述】:

我有一个存储在City 表中的城市列表。假设我想生成动态路由,可以在本例中通过resource.namecity.name 访问。

我希望能够访问/amsterdam/berlin。怎么样?

对于信息,我正在使用 friendly_id gem,所以如果这更有意义的话,已经有了 slug 列。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routing slug friendly-id


    【解决方案1】:

    假设您正确设置了friendly_id:

    match '/cities/:name' => 'cities#show'
    

    resources :cities
    

    来自friendly_id gem 的快速入门

    class City < ActiveRecord::Base
      extend FriendlyId
      friendly_id :name, use: :slugged
    end
    

    还有:

    # If you're adding FriendlyId to an existing app and need
    # to generate slugs for an existing model, do this from the
    # console, runner, or add a Rake task:
    
    City.find_each(&:save)
    

    这是一个 RailsCast:http://railscasts.com/episodes/314-pretty-urls-with-friendlyid?view=asciicast

    【讨论】:

      【解决方案2】:

      在您的路线文件的末尾,添加以下内容:

      match '*id' => 'cities#show
      

      然后在你的 CitiesController 中:

      def show
        @city = City.find(params[:id])
        # ...
      end
      

      【讨论】:

        【解决方案3】:

        不知道这是否有帮助..但我总结了我在项目中使用的要点。

        https://gist.github.com/1908782

        它主要适用于我所做的事情,因为我的路线文件通常非常简洁。

        它的美妙之处在于,如果您尝试访问一条不存在的路径,它不会到达任何路线!

        顺便说一句,这在 4.0 版本中被破坏了。在撰写本文时,您需要将以下内容放入您的 gemfile。

        gem 'friendly_id', :git => 'git://github.com/norman/friendly_id.git'
        

        gem 'friendly_id', :git => 'https://github.com/norman/friendly_id.git'
        

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-12
          • 1970-01-01
          • 2014-03-31
          • 1970-01-01
          • 1970-01-01
          • 2020-04-16
          相关资源
          最近更新 更多