当我想要创建一篇文章时,单击“创建文章”按钮后会得到此错误。
没有路由匹配{:action=>“显示”,:controller=>“项目”,: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%>
发布于 2016-08-26 02:34:32
当您创建一个无效的文章时,它将给您missing required keys: [:id]
,因为它失败了@article.save
,它将redirect_to article_path(@article)
,在本例中,@article.id是nil
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
如果redirect_to article_path(@article)
是真的,只需移动@article.save
即可。
def create
@article = Article.new(article_params)
if @article.save
flash[:notice] = "Your Article was Created"
redirect_to article_path(@article)
else
render 'new'
end
end
编辑:
我克隆了您的回购程序,在不使用user_id
的情况下创建这篇文章时存在问题。添加了底部的变化,它似乎正在发挥作用,如预期。
def create
@article = current_user.articles.build(article_params)
if @article.save
flash[:notice] = "Your Article was Created"
redirect_to article_path(@article)
else
render 'new'
end
end
希望这能帮上忙!
发布于 2016-08-26 02:45:43
您得到了这个错误,因为呈现和重定向都在@article.save fails.So中被执行--在其他部分,它将呈现为新的,并再次重定向以id = nil显示页面。
def create
@article = Article.new(article_params)
if @article.save
flash[:notice] = "Your Article was Created"
redirect_to article_path(@article.id) # or @article
else
render 'new'
end
end
https://stackoverflow.com/questions/39163536
复制相似问题