我想創建一個簡單的博客與rails 5.我的應用程序有一個職位,用戶,類別和評論model.Everything工作正常,除了我不能讓它工作編輯並摧毀徵求意見的行動。
這裏是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根(到:「帖子#索引」) 結束 –