路由控制器#显示方法,例如控制器#索引在导轨中的方式



嗨,我是Rails的新手。对不起,如果我不能正确地定义这个问题。

我想要的是:

domain.com/posts/1-sample-post

要像这样路由:

domain.com/1-sample-post

如何在铁轨路线中实现这一目标?我已经尝试搜索将近3个小时。在PHP框架中,这很容易。我认为这也很容易。

我忘了提到我的静态页面上安装了high_voltage宝石。

做到了:

#routes.rb
resources :posts
get '/:id' => 'posts#show'

现在无法渲染我的High_voltage页面。

更新解决方案:

所以这是我们在路线上所做的:

Rails.application.routes.draw do
  resources :authors
  constraints(lambda { |req| Author.exists?(slug: req.params["id"]) }) do
     get '/:id' => 'authors#show'
  end
  devise_for :users
  resources :posts
  constraints(lambda { |req| Post.exists?(slug: req.params["id"]) }) do
    get '/:id' => 'posts#show'
  end
end

请注意,仅使用一个存在很重要?在这里查询,因为它比其他方法非常快,因此它不会吃太多的加载时间来渲染记录。

特别感谢下面有很多帮助的人。nathanvda,rwold和tai。

,所以另一个答案正确建议了

之类的东西
get '/:id', to: 'posts#show'

,但这是一条接收路线,如果没有其他路线定义,则如果将其配置为在根上供应页面,则该路线将捕获所有路线,也将捕获您的高压。现在,您有两个接收器:一个可以找到一个静态页面,另一个可以找到帖子。

最好的解决方案在这种情况下,恕我直言是要明确静态页面(因为我认为不会有那么多?(

(
get '/about' => 'high_voltage/pages#show', id: 'about'
get '/:id' => 'posts#show'

如果您有很多页面,那么在另一条路线上只展示高压似乎最简单吗?例如。像

get '/pages/:id' => 'high_voltage/pages#show' 
get '/:id' => 'posts#show' 

在这两种情况下

# config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.routes = false
end

[更新:添加特殊控制器以同时考虑帖子和页面]

这样添加HomeController

class HomeController < ApplicationController
  # include the HighVoltage behaviour --which we will partly overwrite 
  include HighVoltage::StaticPage    
  def show
    # try to find a post first 
    @post = Post.where(id: params[:id).first 
    if @post.present? 
      render 'posts/show'
    else 
      # just do the high-voltage thing
      render(
        template: current_page,
        locals: { current_page: current_page },
      )
    end 
  end 
end 

当然我没有测试此代码,但我认为这应该让您开始。您也可以重定向到帖子控制器,而不是进行帖子的渲染,这可能更容易(并且您将完全使用PostsController(,但会添加重定向并更改URL。

在您的路线中,您将不得不写

get '/:id', 'home#show'   

在您的routes.rb文件中:

get '/:id-sample-post', to: 'posts#show', as: :sample_post

假设posts是您的控制器,并且show是带有给定ID的文章视图的动作。

OP评论后编辑:as: :sample_post子句应创建一个可以调用为<%= link_to "Show", sample_post %>的辅助sample_post_path

相关内容

最新更新