【发布时间】:2016-08-26 09:56:54
【问题描述】:
当我想创建文章时,单击创建文章按钮后出现此错误
没有路由匹配 {:action=>"show", :controller=>"articles", :id=>nil} 缺少必需的键:[:id]
虽然我确保在创建文章之前有一个用户已登录。这是我的代码:
articles_controller.rb
class ArticlesController < ApplicationController
before_action :require_user , except:[:index,:show]
def index
@articles = Article.all
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
flash[:notice] = "Your Article was Created"
else
render 'new'
end
redirect_to article_path(@article)
end
def show
@article = Article.find(params[:id])
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
flash[:notice] = "Your Article was Updated"
redirect_to article_path(@article)
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
flash[:notice] = "Your Article was deleted"
redirect_to articles_path(@article)
end
private
def article_params
params.require(:article).permit(:title,:description)
end
结束
users_controller.rb
class UsersController < ApplicationController
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "You Signed up successfully"
redirect_to articles_path
else
render 'new'
end
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
flash[:success]= "Your user was updated"
redirect_to articles_path
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:username,:email,:password)
end
结束
views/new.html
<h1>New Article</h1>
<%= form_for @article do |f| %>
<p>title<%= f.text_field :title %></p><br>
<p>description<%= f.text_area :description %></p>
<%= f.submit "Create" %>
<%end%>
这里是 my github repo
【问题讨论】:
-
请检查您的创建文章按钮链接,它会将您重定向到显示文章控制器的操作
-
在您的代码
<li> <%= link_to "New", new_article_path(@article)%></li>中。您不需要在new_article_path中提供参数。否则,它会检查没有id的文章,正如 navin 所说。 -
虽然我删除了参数,但它仍然显示错误。
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2