ArticlesController#show中的ActiveRecord :: RecordNotFound无法找到没有ID的文章

时间:2015-02-05 00:03:41

标签: ruby-on-rails ruby params

我正在尝试向db提交一些数据,但是当我尝试检索这些数据时,表明找不到没有ID.ils 4.0.1的文章。 我正在使用ruby 2.0.0和ra

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

结束

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

物品/ 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>

物品/ 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 个答案:

答案 0 :(得分:2)

在实际保存文章之前,您正在重定向。

此:

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

应该是:

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

如果你想添加一些错误处理:

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