【问题标题】:How to remove controller name from url using friendly_id如何使用friendly_id从url中删除控制器名称
【发布时间】:2016-07-21 21:47:44
【问题描述】:

我已安装并使用friendly_id 从我的网址中删除博客ID,并将其替换为博客标题。但是,我还需要从 url 中删除控制器名称:

当前:appname/blogs/one-of-the-blog-posts

我想要什么:appname/one-of-the-blog-posts

我这样做是因为我正在为某人重建一个网站,他们的 Twitter 帖子链接到我正在替换的当前网站,但这些帖子的链接格式如下:appname/one-of-the -博客帖子。由于这些帖子无法通过 twitter 更新,这是我能想到的让它们链接到我正在构建的新站点的唯一方法。任何帮助或建议将不胜感激。我已经搜索了谷歌一段时间,但无法找到明确的答案。提前致谢。

路线

AppName::Application.routes.draw do

  root 'pages#index'
  get 'about', to: 'pages#about'
  get 'contacts', to: 'contacts#new'
  resources 'contacts', only: [:new, :create]
  get 'locations/tampa', to: 'locations#tampa'
  get 'locations/jacksonville', to: 'locations#jacksonville'
  get 'locations/orlando', to: 'locations#orlando'
  get 'locations/st_petersburg', to: 'locations#stpetersburg'
  resources :locations do
    resources :photos, only: :create
  end


  resources 'blogs'


  get 'faqs', to: 'pages#faqs'
  get 'whats_included', to: 'pages#whats_included'

end

博客控制器

class BlogsController < ApplicationController
before_action :set_blog, only: [:edit, :update, :show]

  def index
    @blogs = Blog.order("created_at DESC")
  end
  def new
    @blog = Blog.new
  end
  def create
    @blog = Blog.new(blog_params)
    if @blog.save
      flash[:notice] = "New Blog Added"
      redirect_to blogs_path
    else
      flash.now[:error] = 'Cannot Create Blog'
      render 'new'
    end
  end
  def edit

  end
  def update
    @blog.update_attributes(blog_params)
    redirect_to blogs_path(@blog)
  end
  def show
    @location = Location.all
  end

  private

  def set_blog
    @blog = Blog.friendly.find(params[:id])
  end
  def blog_params
    params.require(:blog).permit(:title, :description, :date, :property, :city, :author)
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 url-routing friendly-id


    【解决方案1】:

    我认为你应该能够做到:

    AppName::Application.routes.draw do
    
      root 'pages#index'
      get 'about', to: 'pages#about'
      get 'contacts', to: 'contacts#new'
      resources 'contacts', only: [:new, :create]
      get 'locations/tampa', to: 'locations#tampa'
      get 'locations/jacksonville', to: 'locations#jacksonville'
      get 'locations/orlando', to: 'locations#orlando'
      get 'locations/st_petersburg', to: 'locations#stpetersburg'
      resources :locations do
        resources :photos, only: :create
      end
    
      get 'faqs', to: 'pages#faqs'
      get 'whats_included', to: 'pages#whats_included'
    
      resources 'blogs', path: '/'
    end
    

    不过,如果您采用这种方法,则需要谨慎管理您的路线。

    【讨论】:

    • 我试过这个,但不幸的是我得到一个错误:ActiveRecord::RecordNotFound
    猜你喜欢
    • 2018-01-10
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2015-06-17
    相关资源
    最近更新 更多