【问题标题】:Rails nested routes for simple blog用于简单博客的 Rails 嵌套路由
【发布时间】:2016-07-24 23:39:12
【问题描述】:

我需要为我的博客以及博客下的每篇文章制作页面。它应该看起来像这样example.com/blog/my_first_post。帖子是静态 HTML 文件,我不使用任何数据库。

这是我的路线:

  get 'blog' => 'static_pages#blog' do
    get '/my_first_post' => 'blog#my_first_post' 
  end

这是我的 StaticPages 控制器:

  ...

  def blog
    def my_first_post
    end
  end

  ...

博客页面可以正常工作,但帖子无法正常工作。

【问题讨论】:

  • 你到底想要什么?你有posts 桌子吗?
  • 请详细解释您的问题,您在说什么帖子?是发布请求还是您的文字发布模块?
  • 只是 /blog 页面下的静态 html。没有数据库! @7urkm3n

标签: ruby-on-rails ruby-on-rails-4 routes


【解决方案1】:

要获得此example.com/blog/my_first_post,您的路线应如下所示 -

get 'blog' => 'static_pages#blog'
get 'blog/my_first_post' => 'static_pages#my_first_post'

你的控制器应该是这样的-

class StaticPagesController < ApplicationController
  def my_first_post
  end

  def blog
  end
end

【讨论】:

  • @DanielsV 检查更新的答案。路线将达到BlogsController my_first_post 动作。将您的逻辑放入my_first_post 方法中。
  • 没有博客控制器之类的东西。一切都在“static_pages 控制器”@dkp
  • @DanielsV 好的,现在检查更新的答案。我已经更新了路线和控制器。确保您在 StaticPagesController 中保留了 my_first_post 操作
【解决方案2】:

检查这个:但是一件事

如果它只是静态页面,那么最好如下所示使用。

get 'blog/my_first_post' => 'static_pages#my_first_post'

如果它在其中,则不能像 view 那样调用该方法。把它变成这样。

  def blog
  end

  def my_first_post
  end

【讨论】:

    【解决方案3】:

    使用下面,上面的资源:如果存在博客

    get 'blog/my_first_post'
    

    【讨论】:

      【解决方案4】:

      试一试:

      get 'blog/my_first_post', to: Proc.new { |env|
          [
            200,
            {"Content-Type" => "text/html"},
            [File.read("public/my_first_post.html")] // where you static files are
          ]
        }
      

      在您的情况下,控制器是多余的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-13
        • 1970-01-01
        相关资源
        最近更新 更多