【发布时间】: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