我有用户和广告系列模型。我在用户和网址下嵌套广告系列如下所示:
http://localhost:3000/user-slug/campaign-slug
路线:
resources :users, :path => '' do
resources :campaigns, :path => ''
end
广告系列模型:
class Campaign < ActiveRecord::Base
...
extend FriendlyId
friendly_id :title, use: :history
...
end
我的用户模型没有使用历史记录。
广告系列控制器(来自friendly_id指南):
class CampaignsController < ApplicationController
before_filter :find_campaign
def show
@campaign = Campaign.friendly.find(params[:id])
end
private
def find_campaign
@campaign = Campaign.friendly.find(params[:id])
# If an old id or a numeric id was used to find the record, then
# the request path will not match the post_path, and we should do
# a 301 redirect that uses the current friendly id.
if request.path != campaign_path(@campaign)
return redirect_to @campaign, :status => :moved_permanently
end
end
end
当我访问旧slu to以触发重定向时,我收到此错误:
ActionController::UrlGenerationError in CampaignsController#show
No route matches {:action=>"show", :controller=>"campaigns", :format=>nil, :id=>nil, :user_id=>#<bunch of other stuff in here>} missing required keys: [:id]
我不确定如何调整重定向方法以使其正常工作。
答案 0 :(得分:0)
管理以使其与此一起使用:
def find_campaign
@campaign = Campaign.friendly.find(params[:id])
@user = @campaign.user
# If an old id or a numeric id was used to find the record, then
# the request path will not match the campaign_path, and we should do
# a 301 redirect that uses the current friendly id.
request_slug = params[:id]
if request_slug != @campaign.slug
return redirect_to user_campaign_path(@user, @campaign), :status => :moved_permanently
end
end
我没有比较请求路径,而是比较了斜杠之前没有部分的请求slug。我需要重定向到正确的路线user_campaign_path
。