如何在嵌套资源中使用friendly_id历史记录

如何在嵌套资源中使用friendly_id历史记录

问题描述:

我有User和Campaign模型。在用户和网址,我窝活动是这样的:如何在嵌套资源中使用friendly_id历史记录

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 

当我拜访一个老塞来触发重定向我得到这个错误:

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] 

不知道我应该如何调整重定向方法让它起作用。

设法得到它与这方面的工作:

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 

比较我相比不具有斜线之前的部分请求蛞蝓请求路径相反的。我需要重定向到正确的路线user_campaign_path