2016-06-19 8 views
1

確かに私は数日前にこれについて尋ねましたが、明確ではなかったので、適切な回答が得られませんでした。 私はこのミニブログの事を私のウェブサイトに持っていて、が無効なデータ(すなわちタイトルが短すぎる)を入力した場合、私はをx.com/posts/new(または/ edit)からリダイレクトポストインデックスが存在しないにもかかわらず(:ルートにインデックスが追加されていますが)、ポストインデックスは存在しません(x.com/posts)。バグ:インデックスが存在しないときのインデックスへのルーティング

ポストコントローラ

class PostsController < ApplicationController 
before_action :find_post, only: [:show, :edit, :update, :destroy] 
before_action :admin_user, except: [:show] 

    def show 

    end 

    def new 
    @post = current_user.posts.build 
    @categories = Category.all.where(belongs_to_posts: true) 
    end 

    def create 
    @post = current_user.posts.build(post_params) 

    if @post.save 
     redirect_to @post 
    else 
     render 'new' 
    end 
    end 

    def edit 
    @categories = Category.all.where(belongs_to_posts: true) 
    end 

    def update 
    if @post.update(post_params) 
     redirect_to @post 
    else 
     render 'edit' 
    end 
    end 

    def destroy 
    @post.destroy 
    redirect_to root_path 
    end 

    private 

    def find_post 
     @post = Post.find(params[:id]) 
    end 

    def post_params 
     params.require(:post).permit(:description, :title, :image, :categories_id) 
    end 

    def admin_user 
     redirect_to(root_url) unless current_user.admin? 
    end 
end 

経路

Rails.application.routes.draw do 
     root 
     ...   
     get 'galleries/accept'    => 'galleries#accept' 
     resources :galleries 
     resources :photos 
     resources :posts,     except: [:index] 
     resources :categories 
     resources :documents 
    end 

ポスト

= simple_form_for @post do |f| 
    = f.input :image 
    = f.input :title 
    = f.input :categories_id, :collection => @categories, label_method: :name, value_method: :id 
    = f.cktext_area :description, data: {no_turbolink: true}, :ckeditor => {:toolbar => 'mini'} 
    = f.button :submit 

それを_formメインページに投稿を表示するため、インデックスが存在しないことに気付くかもしれません。ご協力ありがとうございました!

答えて

0

あなたの質問にお答えするには、私はあなたのrake routesを調べるべきだと言いたいと思います。あなたが見ることの1つは、あなたのPost#createアクションが/postsになります。これは、RESTfulなアプリケーションのルートが新しいリソースのために定義される方法です。

RESTfulアプリケーションを使用する場合、リソースを処理するときに呼び出されるアクションは、主にリソースで呼び出されるHTTPMethodによって決まります。

indexが、それはまだあなたを示さない理由今、あなたは不思議に思うでしょう

Cheatsheet: 

create => POST to /posts 
index => GET to /posts 
update => PATCH to /posts/:id 
show => GET to /posts/:id 
destroy => DELETE to /posts/:id 
edit => GET to /posts/:id/edit 
new => GET to /posts/new 

\postsルートにGET要求によってトリガーされる一方でcreateアクションは、\postsルートへPOST要求によってトリガーされます同じページ上にposts/newフォームが表示されています。これは、Post#createアクションでrender 'new'メソッドを呼び出したためです。つまり、この(作成)アクションでnewビューを表示するということです。

私はこれをより良く理解していただきたいと思います。

+0

非常にありがとう、それは非常に教育的でした!しかし、私はまだ問題に対処する方法はまだ分かっていません。私はそれが '' @ post.save redirect_to @post else render 'new''についてのものだと思いますか?どうすればこの問題を解決できますか? – Ivan

関連する問題