如何为像美国/德州/奥斯汀这样的城市和州制作friendly_id网址

时间:2014-09-23 00:05:44

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

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

united-states/texas/austin

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

我希望第二个简单:

united-states/colorado/austin

那么我如何让friendly_id停止创建独特的slu ,,而确保城市slug在按国家和州划分时是唯一的呢?

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

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

这只是看看slug,并不关心城市是嵌套资源。

这是我的设置:

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

enter image description here

更新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) %>

1 个答案:

答案 0 :(得分:0)

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

如果你踢了我一点**也许我会让自己最终请求补丁。