嗨,我正在尝试向我的 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