【问题标题】:How do I make friendly_id URLs for city and state like united-states/texas/austin如何为美国/德克萨斯州/奥斯汀等城市和州创建友好 ID URL
【发布时间】:2014-09-23 00:05:44
【问题描述】:

所以我有 2 个不同的链接:

united-states/texas/austin

和:

united-states/colorado/austin-14be76ea-77e2-4f0e-8540-0103ad72cd7a

我希望第二个简单:

united-states/colorado/austin

那么我如何获得friendly_id 以停止创建独特的slug,而是确保city slug 在按国家和州划分时是唯一的?

此外,在我的控制器中,我如何定位正确的城市(按国家和州划分)?

@city = City.friendly.find(params[:id])

这只是看着蛞蝓,并不关心城市是一个嵌套资源。

这是我的设置:

class City < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, :use => :scoped, :scope => [:homeland, :region]
  belongs_to :region
  belongs_to :homeland
end

class Region < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, :use => :scoped, :scope => :homeland
  belongs_to :homeland
  has_many :cities
end

#Had to use Homeland as Country was in use
class Homeland < ActiveRecord::Base 
  extend FriendlyId
  friendly_id :name, use: :slugged
  has_many :regions
  has_many :cities, through: :regions
end

Routes.rb

  resources :homelands, :path => '' do
    resources :regions, :path => '' do 
      resources :cities, :path => ''
    end
  end

更新:Michal 来了

更新 2:我现在的修复

删除:

  resources :homelands, :path => '' do
    resources :regions, :path => '' do 
      resources :cities, :path => ''
    end
  end

添加:

  get "local/:id", to: "homelands#show", as: 'homeland'
  get "local/:homeland_id/:id", to: "regions#show", as: 'region'
  get "local/:homeland_id/:region_id/:id", to: "cities#show", as: 'city'

对于链接:

<%= link_to region.name, region_path(region.slug, homeland_id: @homeland.slug) %>

【问题讨论】:

  • 您具体使用哪个版本的 FriendlyId?哪个 Rails 版本?
  • friendly_id (5.0.4), rails (4.1.4)

标签: ruby-on-rails nested-resources friendly-id


【解决方案1】:

FriendlyId 中有一个错误导致了这种情况。见https://github.com/norman/friendly_id/issues/536

如果你踢我的**,也许我最终会让自己拉请求补丁。

【讨论】:

  • 我正要恢复编辑,直到我看到这个答案。打得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
  • 2017-10-20
  • 2011-01-14
相关资源
最近更新 更多