【发布时间】:2019-12-02 15:22:13
【问题描述】:
我尝试为 cmets 制作简单的投票系统。
只需一个按钮“投票”,如果用户已经点击,则变为“删除投票”。一切似乎都有效,除了语音删除功能。如果我单击“删除投票”,则会出现错误 Couldn't find Post with 'id'=11。
我不明白为什么会这样,因为事实上,这是一种用于投票和取消投票的方法。只有在一种情况下一切正常,但在另一种情况下则不行。
votes_controller:
class VotesController < ApplicationController
before_action :find_comment
before_action :find_vote, only: [:destroy]
def create
if already_voted?
flash[:notice] = "You can't like more than once"
else
@comment.votes.create(author_id: current_author.id)
end
redirect_to post_path(@post)
end
def destroy
if !(already_voted?)
flash[:notice] = "Cannot unlike"
else
@vote.destroy
end
redirect_to post_path(@post)
end
private
def find_comment
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:comment_id])
end
def already_voted?
Vote.where(author_id: current_author.id, comment_id:
params[:comment_id]).exists?
end
def find_vote
@vote = @comment.votes.find(params[:id])
end
end
投票 _comment.html.erb 中的元素:
<% pre_vote = comment.votes.find { |vote| vote.author_id == current_author.id} %>
<% if pre_vote %>
<%= button_to 'Delete Vote', post_comment_vote_path(comment, pre_vote), method: :delete %>
<% else %>
<%= button_to 'UpVote', post_comment_votes_path(post, comment), method: :post %>
<% end %>
<p><%= comment.votes.count %> <%= (comment.votes.count) == 1 ? 'Like' : 'Likes'%></p>
UPD 这篇文章的 id - 3,而不是 11。 该评论的 ID 为 11。 出于某种原因,它在删除喜欢的过程中混淆了一切。
UPD 2
迁移:
def change
create_table :votes do |t|
t.references :comment, null: false, foreign_key: true
t.references :author, null: false, foreign_key: true
t.timestamps
end
end
投票.rb:
class Vote < ApplicationRecord
belongs_to :comment
belongs_to :author
end
comment.rb 和 author.rb : has_many :votes, dependent: :destroy
【问题讨论】:
-
请添加迁移和模型来提问。
标签: ruby-on-rails ruby