【问题标题】:I cannot make a function to delete likes我无法创建删除喜欢的功能
【发布时间】: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


【解决方案1】:

您的删除链接中似乎缺少一个参数。尝试添加post 作为第一个参数:

<%= button_to 'Delete Vote', post_comment_vote_path(post, comment, pre_vote), method: :delete %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    相关资源
    最近更新 更多