私はレールで簡単なブログを作成しようとしています。私のアプリは投稿、ユーザー、カテゴリ、コメントのモデルを持っています。コメントのためのアクションを破壊する。
ここrevelantコントローラlink_toアクションがネストされたリソースのために機能していません。
comments_controller.rb
Class CommentsController < ApplicationController
def new
@comment=Comment.new
@post=Post.find(params[:post_id])
end
def create
@post=Post.find(params[:post_id])
@comment=Comment.new(params.require(:comment).permit(:body))
@comment.user_id=current_user.id
@[email protected]
if @comment.save
redirect_to(post_path(@post))
else
render('new')
end
end
def edit
@post=Post.find(params[:post_id])
end
def update
end
def destroy
@post=Post.where(id: params[:post_id])
@comment=Comment.where(post_id: params[:post_id],id: params[:id])
@comment.destroy(params[:post_id])
redirect_to(post_path(@post))
end
end
posts_controller.rb
class PostsController < ApplicationController
before_action(:post_find,only: [:show,:edit,:update,:destroy])
before_action(:authenticate_user!,except: [:index,:show])
before_action(:owner?,only: [:edit,:update,:destroy])
before_action(:find_categories,only: [:new,:create,:edit,:update])
def index
if params[:category].blank?
@posts=Post.all
else
@category_id=Category.find_by(name: params[:category]).id
@posts=Post.all.where(category_id: "#{@category_id}").order("created_at DESC")
end
end
def new
@post=Post.new
end
def create
@post=Post.new(post_params)
@post.user_id=current_user.id
@post.category_id=params[:category_id]
if @post.save
redirect_to(root_path)
else
render('new')
end
end
def show
end
def edit
end
def update
@post.category_id=params[:category_id]
if @post.update(post_params)
redirect_to(post_path(@post))
else
render('edit')
end
end
def destroy
@post.destroy
redirect_to(posts_path)
end
private
def post_params
params.require(:post).permit(:title,:body,:category,:category_id)
end
def post_find
@post=Post.find(params[:id])
end
def owner?
if user_signed_in?
if @post.user.id!=current_user.id
redirect_to(root_path)
end
end
end
def find_categories
@categories=Category.all.map{|c| [c.name,c.id]}
end
end
ポスト/ show.html.erb(revelant部)
<h4>
Comments
<% if user_signed_in? %>
| <%= link_to("New comment",new_post_comment_path(@post)) %>
<% end %>
</h4>
<ul>
<% @post.comments.each do |f| %>
<li>
<%= f.body %> |
by <%= f.user.email %> |
<%= link_to("Delete",post_comment_path(f),method: :delete) %>
</li>
<% end %>
</ul>
ありますどんなアイデアが間違っているの?
エラーが発生しますか? – Pavan
何誤りであるとコメントのルートを掲示し、同様に –
ルートを投稿してください:(:ユーザー)Rails.application.routes.drawは devise_forを行う \tリソース(:掲載)(:コメント) \t \tリソースを行う \t最後に \tルート( "posts#index") end –