您好我正在尝试为我的Pins模型添加评论。我可以添加评论,但似乎无法为我的编辑和删除操作找到正确的链接。
评论控制器
class CommentsController < ApplicationController
before_action :find_pin
before_action :find_comment, only: [:destroy, :edit, :update]
def index
end
def show
end
def new
@comment = Comment.new
end
def create
@comment = @pin.comments.build(comment_params)
@comment.user_id = current_user.id
@comment.save
if @comment.save
flash[:notice] = "Created comment"
redirect_to pin_url(@pin.id)
else
render 'new'
end
end
def edit
end
def update
@comment = @pin.comments.find(params[:id])
end
def destroy
@comment.destroy
flash[:notice] = "Deleted Comment"
redirect_to pin_url(@pin.id)
end
private
def find_pin
@pin = Pin.find(params[:id])
end
def find_comment
@comment = Comments.find(params[:pin_id])
end
def comment_params
params.require(:comment).permit(:content)
end
end
评论表格视图
<%= form_for ([@comment.build]) do |f| %>
<p><%= f.text_area :content %></p>
<p><%= f.submit %></p>
<% end %>
评论显示视图
<%= @comment.each do |comment| %>
<p><%= comment.content %></p>
<% if current_user == comment.user %>
<%= link_to "Edit comment", edit_comment_path(@pin, comment)%>
<%= link_to "Delete comment", [comment.pin,comment], method: :delete %>
<% end %>
<% end %>
路由
Rails.application.routes.draw do
match '/users', to: 'users#index', via: 'get'
match '/users/:id', to: 'users#show', via: 'get'
get 'homes/show'
devise_for :users, :path_prefix => 'd'
resources :pins do
member do
resources :comments
put "like", to: "pins#upvote"
end
end
resources :users, :only =>[:show]
root "pins#index"
end
引脚控制器
class PinsController < ApplicationController
before_action :find_pin, only: [:show, :edit, :update, :destroy, :upvote]
before_action :authenticate_user!, except: [:index, :show]
def index
@pins = Pin.all.order("created_at DESC")
end
def show
@comment= Comment.where(pin_id: @pin).order("created_at DESC")
end
def new
@pin = current_user.pins.build
end
def create
@pin = current_user.pins.build(pin_params)
if @pin.save
redirect_to @pin, notice: "Successfully created new Pin"
else
render 'new'
end
end
def edit
if @pin.user != current_user
redirect_to root_path
end
end
def update
if @pin.update(pin_params) && @pin.user == current_user
redirect_to @pin, notice: "Pin was successfully updated"
else
render 'edit'
end
end
def destroy
if @pin.user == current_user
@pin.destroy
redirect_to root_path
else
redirect_to root_path, notice: "Not Your Pin!"
end
end
def upvote
@pin.upvote_by current_user
redirect_to :back
end
private
def pin_params
params.require(:pin).permit(:title, :description, :image)
end
def find_pin
@pin = Pin.find(params[:id])
end
end
先谢谢,我已经坚持了一段时间 由于某种原因,引脚ID和注释ID最终相同或类似 http://localhost:3000/pins/30/comments/30
答案 0 :(得分:1)
运行rake routes
以检查应用中的所有路线。您会发现所有路线都将以复数形式命名。因此edit_pins_comments_path
仅适用于您的申请。但正如您的模型所示,每个引脚都会有很多评论。要完成此任务,您需要将注释资源嵌套到每个引脚成员中。所以你的路线将如下所示。
resources :pins do
member do
resources :comments
put "like", to: "pins#upvote"
put "favorite", to: "pins#favorite"
end
end
此代码将生成edit_comment_path
,comment_path
等。