我尝试使用回形针在我的博客设计中包含图像。我一直收到错误: ArticlesController #create中的ActionController :: UrlGenerationError 没有路由匹配{:action =>“show”,:controller =>“articles”}缺少必需的键:[:id] 现在,每当我点击提交按钮创建新文章时,它都会显示“无法找到没有ID的文章”。我还尝试通过链接访问节目页面的视图,但我不能。
提取的来源(第30行):
这是我的文章控制器
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
@comment = Comment.new
@comment.article_id = @article.id
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
@article.save
redirect_to article_path
end
def edit
@article = Article.find(params[:id])
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
def update
@article = Article.find(params[:id])
@article.update(article_params)
flash.notice = "Article '#{@article.title}' Updated!"
redirect_to article_path
end
def article_params
params.require(:article).permit(:title, :body, :tag_list, :image)
end
end
这是我的文章助手:
module ArticlesHelper
def article_params
params.require(:article).permit(:title, :body, :tag_list, :image)
end
end
这是我的文章/ show.html.erb
<h1><%= @article.title %></h1>
<p>
Tags:
<% @article.tags.each do |tag| %> <%= link_to tag.name, tag_path(tag) %>
<% end %>
</p>
<% if @article.image.exists? %>
<p><%= image_tag @article.image.url %></p>
<% end %>
<p><%= @article.body %></p>
<h3>Comments (<%= @article.comments.size %>)</h3>
<%= render partial: 'articles/comment', collection: @article.comments %>
<%= render partial: 'comments/form' %>
<%= link_to "<< Back to Articles List", articles_path %>
<%= link_to "delete", article_path(@article), method: :delete, data: {confirm: "Really delete the article?"} %>
<%= link_to "edit", edit_article_path(@article) %>
这是我的路线档案
TheBlog::Application.routes.draw do
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
get 'article' => 'articles#show'
resources :users
resources :articles do
resources :comments
end
resources :tags
end
答案 0 :(得分:0)
该错误告诉您,当您尝试在:id
中生成文章展示路线时,您错过了ArticlesController
参数。
resources :articles
文件中的config/routes
行将生成许多路线辅助方法,包括显示路线的article_path
。默认情况下,此辅助方法需要一个参数 - 一个可以转换为前面提到的:id
参数。此参数应该是文章ID,或者更常见的是文章的实例。您需要告诉Rails哪个文章显示页面发送给用户,对吗?
因此,您需要将文章实例传递给article_path
操作中create
的调用(并显示update
)。以下是对create
操作的重写:
def create
@article = Article.new(article_params)
@article.save
redirect_to article_path(@article)
end