如何设置路径?
运行rails应用程序时出现以下错误:
No route matches {:action=>"show", :controller=>"practice"}, missing required keys: [:id]
这是我的index.erb.html文件
<h3>Please fill the following details</h3>
<hr>
<%= form_with scope: :welcome , local: true do |f| -%>
<b><i>Name</b></i>:            <%= f.text_field :name %> </br></br>
<b><i>Address</b></i>:         <%= f.text_area :address %> </br></br>
<b><i>City</b></i>:    <%= f.text_field :city %> </br></br>
<%= f.submit "Submit", class: "btn-submit" %>
<% end %>
这是我的routes.rb文件。
Rails.application.routes.draw do
resources :practice
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
这是我的Controller文件:
class PracticeController < ApplicationController
def new
@welcome= Welcome.new;
end
def index
@welcome= Welcome.new;
end
def show
@welcome = Welcome.find(params[:id])
end
def create
@welcome=Welcome.new(params.require(:welcome).permit(:name,:address,:city)) ;
if @welcome.save
flash[:notice]="Successfully Registered"
redirect_to practice_path
else
flash[:notice]="Error while registering"
render:new
end
end
end
这是我的show.html.erb文件:
<p>
<strong>Name:</strong>
<%= @welcome.name %>
</p>
<p>
<strong>Address:</strong>
<%= @Welcome.address %>
</p>
<p>
<strong>City:</strong>
<%= @welcome.city%>
</p>
&#13;
我没有为show.html.erb文件设置任何link_to帮助器。
答案 0 :(得分:0)
声明路线时使用复数形式:
# bad
resources :practice
# good
resources :practices
要重定向到索引路径,您需要重定向到practices_path
:
def create
@welcome = Welcome.new(practice_params)
if @welcome.save
redirect_to practices_path, notice: "Successfully Registered"
else
render :new, notice: "Error while registering"
end
end
private
def practice_params
params.require(:welcome).permit(:name,:address,:city)
end
如果您想要重定向到新创建的记录,只需将其传递给redirect_to
:
redirect_to @welcome, notice: "Successfully Registered"
您可以看到rails routes
的完整路线列表(在Rails 4中运行bundle exec rake routes
代替