我的首页有两个按钮
- 注册
- 登录
如果我点击我应该重定向到 new.html.erb
页面,但是当我点击注册按钮时我发现了以下错误。请帮我解决这个错误。
错误:
No route matches [POST] "/posts/new"
我的代码片段如下。
在posts/index.html.erb
<h1>Index page</h1>
<h1>Register Here</h1>
<hr />
<p>
<%= button_to "REGISTER",posts_new_path%>
</p>
<p>
<%= button_to "LOGIN" %>
</p>
在posts/new.html.erb
<h1>Register Here</h1>
在controller/posts_controller.rb
class PostsController < ApplicationController
def index
end
def new
@user=User.new
end
end
在config/routes.rb
Rails.application.routes.draw do
root "posts#index"
get "posts/new" => "posts#new"
#resources:posts
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
我正在使用 rails version-4
最佳答案
posts_new_path
未在您的应用程序中的任何位置定义。
我建议您看一下 Rails routing guide获得更深入的理解,但解决此问题的最快方法是将 routes.rb 文件更改为:
Rails.application.routes.draw do
root "posts#index"
get "posts/new" => "posts#new", as: new_post
#resources:posts
end
在你看来:
<%= button_to "REGISTER",new_post_path%>
在路由中使用 as
方法创建一个命名路由,使用在末尾用 path
或 url
指定的短语,它可以然后在您的 View 中使用。
您可以使用短语 resources :posts
,它会在您的应用程序中为 7 个 CRUD 操作公开许多命名路由。阅读指南,因为它可能对您有好处,具体取决于您的应用程序的结构。
关于ruby-on-rails - ROR 中的路由错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498785/