Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在不需要前缀的情况下为虚拟URL设置Rails routes.rb_Ruby On Rails_Ruby_Ruby On Rails 4_Seo_Rails Routing - Fatal编程技术网

Ruby on rails 如何在不需要前缀的情况下为虚拟URL设置Rails routes.rb

Ruby on rails 如何在不需要前缀的情况下为虚拟URL设置Rails routes.rb,ruby-on-rails,ruby,ruby-on-rails-4,seo,rails-routing,Ruby On Rails,Ruby,Ruby On Rails 4,Seo,Rails Routing,我希望设置routes.rb来支持不需要前缀的虚荣URL。例如,这里不需要mysite.com/articles/seo url中的“articles/”。我只想在这里mysite.com/seo url 如何设置routes.rb,以便在url访问我的站点时:routes.rb查看url中seo url的值是否与表Article.seo\u url中我的数据库中的记录匹配。如果未找到匹配项,则routes.rb应向下移动routes.rb文件的其余部分。开始的基本代码: # config/ro

我希望设置routes.rb来支持不需要前缀的虚荣URL。例如,这里不需要mysite.com/articles/seo url中的“articles/”。我只想在这里
mysite.com/seo url


如何设置routes.rb,以便在url访问我的站点时:routes.rb查看url中
seo url的值是否与表
Article.seo\u url
中我的数据库中的记录匹配。如果未找到匹配项,则routes.rb应向下移动routes.rb文件的其余部分。

开始的基本代码:

# config/routes.rb

Rails.application.routes.draw do
  resources :posts
  resources :authors

  constraints(PostUrlConstrainer.new) do
    get "/:id", to: "posts#show"
  end
end

# app/constraints/post_url_constrainer.rb

class PostUrlConstrainer
  def matches?(request)
    title = request.path_parameters[:id]
    Post.find_by(title: title)
  end
end

# app/controllers/posts_controller.rb

def set_post
  @post = Post.find_by(title: params[:id])
end
相关文章:

搜索
rails url约束似乎有帮助