Ruby on Rails:新帖子没有保存在博客上

时间:2016-04-10 12:27:59

标签: ruby-on-rails ruby ruby-on-rails-3

我正在进行一项练习,在轨道上创建一个带有ruby的博客。我已准备好发布文章,但是一旦我点击提交按钮,我就被重定向到主页,但文章没有保存。以下是代码

class ArticlesController < ApplicationController
  def index
    @articles = Article.paginate(:page => params[:page], per_page: 5).order('created_at DESC')
  end

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

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(title: params.permit[:title], body: params.permit[:body])

    if @article.save
      redirect_to articles, :notice => "Your post has been saved"
    else
      render :create
    end
  end

end

以下是视图create.html.haml

.container
    .row
        .col-xs-9-
            .panel-title
                %h2 Ecrivez votre article
                = form_for @article do |f|
                    = f.text_field :title
                    = f.text_area :body, size: "60x12"
                    = f.submit "Publier"

然后是route.rb,我不知道它是否可以提供帮助

TP2::Application.routes.draw do
  resources :articles, only: [:index]

  get 'articles' => 'articles#index'

  get 'articles/:id' => 'articles#show'

  get 'articles/new'

  get 'post' => 'articles#create'

  post 'articles' => 'articles#index'

这里完成的是当我尝试发表文章时控制台显示的内容

Started GET "/post" for 127.0.0.1 at 2016-04-10 14:24:56 +0200
Processing by ArticlesController#create as HTML
   (0.2ms)  BEGIN
   (0.2ms)  ROLLBACK
  Rendered articles/create.html.haml within layouts/application (1.4ms)
Completed 200 OK in 9ms (Views: 4.9ms | ActiveRecord: 0.4ms)


Started POST "/articles" for 127.0.0.1 at 2016-04-10 14:25:10 +0200
Processing by ArticlesController#index as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"FMQmKvZ1t98ZE21VaiBQhm0jKJ9x9BwkXFbh4obfi3Qea0Zax5dgGirfpgcAiQA464GMD2+Qv/eGYrmvEoTZBQ==", "article"=>{"title"=>"Post", "body"=>"New Article test"}, "commit"=>"Publier"}
  Article Load (0.6ms)  SELECT  "articles".* FROM "articles"  ORDER BY created_at DESC LIMIT 5 OFFSET 0
   (0.4ms)  SELECT COUNT(*) FROM "articles"
  Rendered articles/index.html.haml within layouts/application (3.4ms)
Completed 200 OK in 7ms (Views: 5.3ms | ActiveRecord: 1.0ms)

我不明白为什么新文章不会保存。有谁理解为什么?

1 个答案:

答案 0 :(得分:0)

我会简化路线:

Rails.application.routes.draw do
  root to: 'articles#index' # or where you want for the first page

  resources :articles #will give you the correct path and verbs
end

还有articles_controller.rb

class ArticlesController < ApplicationController

 ...

  def create
    @article = Article.new(article_params)

    respond_to do |format|
      if @article.save
        format.html { redirect_to @article, notice: "Article created!" }
      else
        format.html { render action: 'new' }
      end
    end
  end

  private

  def article_params
    params.require(:article).permit(:title, :body)
  end
end