ActiveRecord::RecordNotFound in ArticlesController#show Couldn't find Article without an ID

穿精又带淫゛_ 提交于 2019-12-02 15:06:54

问题


I am trying to submit some data to db and its ok but when i am trying to retrieve those data show that Couldn't find Article without an ID.ils 4.0.1. I am using ruby 2.0.0 and ra

def show
@article=Article.find(params[:id])

end

the ** contain error. 

class ArticlesController < ApplicationController
  def new
  end
  def create
  @article = Article.new(article_params)
  redirect_to @article
  @article.save
  end

 def show
  @article=Article.find(params[:id])
  end
  private
   def article_params

   params.require(:article).permit(:title, :full_name, :email, :phone_number, :message)
  end

   end

articles/show.html.erb

<p>
 <strong>Title:</strong>
 <%= @article.title %>
</p>

<p>
 <strong>Full Name:</strong>
 <%= @article.full_name %>
 </p>

 <p>
 <strong>Email:</strong>
  <%= @article.email %>
  </p>

 <p>
  <strong>Phone Number:</strong>
   <%= @article.phone_number %>
  </p>
  <p>
  <strong>Message:</strong>
   <%= @article.message %>
   </p>

articles/new.html.erb

<h1>New Articles</h1>

 <%= form_for :article, url: articles_path do |f| %>
  <p>
   <%= f.label :title %>
   <%= f.text_field :title %>
  <p>
  <%= f.label :full_name %>
  <%= f.text_field :full_name %>
  </p>
  <%= f.label :email %>
   <%= f.text_field :email %>
   <p>
   <%= f.label :phone_number %>
   <%= f.text_field :phone_number %>
   </p>
   <%= f.label :message %>
   <%= f.text_field :message %>
   <p>
    <%= f.submit :send_message %>
    </p>

   <% end %>

回答1:


You are redirecting before actually saving your article.

This:

def create
  @article = Article.new(article_params)
  redirect_to @article
  @article.save
end

should be:

def create
  @article = Article.new(article_params)
  @article.save
  redirect_to @article      
end

And if you want to add some error handling as well:

def create
  @article = Article.new(article_params)
  if @article.save
    redirect_to @article
  else
    render :new
end


来源:https://stackoverflow.com/questions/28333918/activerecordrecordnotfound-in-articlescontrollershow-couldnt-find-article-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!