use*_*986 10 ruby ruby-on-rails
我收到以下错误:
没有路由匹配{:action =>"show",:controller =>"articles",:id => nil}缺少必需的键:[:id]
以下是显示错误的代码.
<%= form_for :article, url: article_path(@article), method: :patch do |f| %>
Run Code Online (Sandbox Code Playgroud)
什么是这个错误,每当我从上一个屏幕点击编辑时,我想我正在发送文章ID.
这是我的佣金路线输出
Prefix Verb URI Pattern Controller#Action
welcome_index GET /welcome/index(.:format) welcome#index
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root GET / welcome#index
Run Code Online (Sandbox Code Playgroud)
如果你看看你的问题
<%= form_for :article, url: article_path(@article), method: :patch do |f| %>
Run Code Online (Sandbox Code Playgroud)
检查您的网址:article_path(@article)这是您的文章展示操作的路径助手,如果您检查您的佣金路线,它表示您需要一个get请求,但您正在使用patch方法或者您正在尝试编辑文章那么你的路径助手是错误的,因此没有路由错误
固定
要显示一篇文章:
如果你想显示一篇文章而不是form_for使用link_to,默认情况下使用get请求,form_for用于创建文章而不是用于显示文章
<%= link_to "Article", articles_path(@article) %>
Run Code Online (Sandbox Code Playgroud)
要创建或编辑文章:
一个.使用多态网址
如果您想创建文章或编辑文章,那么您可以使用rails多态URL并且不需要指定url选项,rails将在内部处理它.因此,对于创建和编辑文章,您可以使用相同的表单
<%= form_for @article do |f| %>
// your fields
<% end %>
Run Code Online (Sandbox Code Playgroud)
为此,您需要在控制器中使用此功能
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
Run Code Online (Sandbox Code Playgroud)
湾 使用path_helpers
如果您在表单中硬编码url选项,那么它只会带您进行该操作,因此您需要单独的表单
用于创建:
<%= form_for :article, url: article_path do |f| %>
// your fields
<% end %>
Run Code Online (Sandbox Code Playgroud)
用于编辑:
<%= form_for :article, url: article_path(@article) do |f| %>
// your fields
<% end %>
Run Code Online (Sandbox Code Playgroud)