【问题标题】:How to use friendly_id history with nested resources如何将friendly_id 历史记录与嵌套资源一起使用
【发布时间】:2014-09-01 05:56:43
【问题描述】:

我有 User 和 Campaign 模型。我在用户和 URL 下嵌套广告系列如下所示:

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

当我访问旧 slug 以触发重定向时,我收到此错误:

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]

不确定我应该如何调整重定向方法以使其正常工作。

【问题讨论】:

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


    【解决方案1】:

    设法让它与这个一起工作:

      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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 2020-01-19
      相关资源
      最近更新 更多