0

Deseo controlar de que el usuario que este logueado no sea el mismo que hizo la pregunta para evitar de que el usuario logueado vote por sus propias respuestas y preguntas pero que permita ver la fecha.

votes_controller.rb

class VotesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_voteable, only: [:show, :edit, :update, :destroy]

  def create
    @voteable.votes.create(user: current_user)
    redirect_to question_path(question), notice: "A successfully voted..."
  end

  def destroy
    @voteable.votes.where(user: current_user).take.try(:destroy)
    redirect_to question_path(question), notice: "Successfully removed vote..."
  end

  private

    def question
      @voteable.try(:question) || @voteable
    end
end

vote.rb

# == Schema Information
#
# Table name: votes
#
#  id            :integer          not null, primary key
#  voteable_id   :integer
#  voteable_type :string
#  created_at    :datetime         not null
#  updated_at    :datetime         not null
#  user_id       :integer
#

class Vote < ApplicationRecord
  belongs_to :voteable, polymorphic: true
  belongs_to :user

  def  self.voted_by?(user, voteable)
    voteable.votes.find_by(user_id: user.id)
  end

end

questions/show.hrml.erb

<div class="container">
    <div class="row">
        <div class="col-sm-8 col-sm-offset-1">
            <h2 class="title-question"><%= @question.title %></h2>
        </div>
    </div>
    <div class="questions">
        <% if user_signed_in? %>
            <div class="row">
              <div class="col-sm-1 col-sm-offset-1">
                <% vote = Vote.voted_by?(current_user,  @question) %>
                <% if vote %>
                      <%= link_to question_vote_path(@question, vote), remote: true, method: :delete, class: "question-upvote upvote-active" do %>
                          <span class="upvote-arrow"></span>
                          <span class="upvote-count"><%= @question.votes.count %></span>
                      <% end %>
                <% else %>
                      <%= link_to question_votes_path(@question), remote: true, method: :post, class: "question-upvote" do %>
                          <span class="upvote-arrow"></span>
                          <span class="upvote-count"><%= @question.votes.count %></span>
                      <% end %>
                <% end %>
                </div>
                <div class="col-sm-8 body-show-question">
                    <span> <%= markdown(@question.body) %> </span>
                    <span class="comments">
                      <%= render partial: "comments/comments", locals: {commentable: @question} %>
                    </span>
                      <%= render partial: "comments/form", locals: {commentable: [@question]} %>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-8 col-sm-offset-1">
                    <h2>(<%= @question.answers.count %>) Answer(s)</h2>
                </div>
            </div>
            <% @question.answers.each do |answer|  %>
                <div class="row">
                  <div class="col-sm-1 col-sm-offset-1">
                    <% vote = Vote.voted_by?(current_user, answer) %>
                    <% if vote %>
                          <%= link_to question_answer_vote_path(@question, answer), remote: true, method: :delete, class: "question-upvote upvote-active" do %>
                              <span class="upvote-arrow"></span>
                              <span class="upvote-count"><%= answer.votes.count %></span>
                          <% end %>
                    <% else %>
                        <%= link_to question_answer_votes_path(@question, answer, vote), remote: true, method: :post, class: "question-upvote" do %>
                                <span class="upvote-arrow"></span>
                                <span class="upvote-count"><%= answer.votes.count %></span>
                        <% end %>
                    <% end %>
                  </div>
                  <div class="col-sm-8 body-show-question">
                        <span> <%= markdown(answer.body) %> </span>
                        <span class="comments">
                          <%= render partial: "comments/comments", locals: {commentable: answer} %>
                        </span>
                          <%= render partial: "comments/form", locals: {commentable: [answer.question, answer]} %>
                  </div>
                </div>
            <% end %> <!-- end do |answer|-->
            <div class="row">
                <div class="col-sm-8 col-sm-offset-1">
                    <h3 class="head-answer">Your answer</h3>
                    <%= render partial: "answers/form", locals: {question: @question} %>
                </div>
            </div>
        <% else %>
            <div class="row">
                <div class="col-sm-1 col-sm-offset-1">
                    <div class="question-upvote">
                        <span class="upvote-arrow"></span>
                        <span class="upvote-count"><%= @question.votes.count %></span>
                    </div>
               </div>
               <div class="col-sm-8 body-show-question">
                    <span> <%= markdown(@question.body) %> </span>
                    <span class="comments">
                        <%= render partial: "comments/comments", locals: {commentable: @question} %>
                    </span>
               </div>
            </div>
            <div class="row">
                <div class="col-sm-8 col-sm-offset-1 ">
                    <div>
                        <h2>(<%= @question.answers.count %>) Answer(s)</h2>
                    </div>
                </div>
           </div>
          <% @question.answers.each do |answer|  %>
            <div class="row">
                <div class="col-sm-1 col-sm-offset-1">
                  <div class="question-upvote">
                     <span class="upvote-arrow"></span>
                     <span class="upvote-count"><%= answer.votes.count %></span>
                  </div>
                </div>
                <div class="col-sm-8 body-show-question">
                      <span> <%= markdown(answer.body) %> </span>
                      <span class="comments">
                        <%= render partial: "comments/comments", locals: {commentable: answer} %>
                      </span>
                </div>
            </div>
          <% end %> <!-- end do |answer|-->
    </div><!-- end  class questions-->
  <% end %>
</div>

Deduzco debería invocar el método una vez se pregunte por la variable vote en cada parte de la vista para la pregunta y la respuesta.

¿Cómo puedo extraer el usuario de la pregunta seleccionada y pasarle el usuario logueado a un método para que dependiendo si es true o false no tenga acceso al link que crea el vote?

1 respuesta 1

1

En lugar de negar el acceso al link, podrías optar por enviar un mensaje al usuario cuando intente votar en alguna de sus publicaciones (tal como lo hace SO); esto podrías lograrlo comparando @voteable.user_id contra current_user.id y permitir el voto cuando sean valores distintos, por ejemplo:

class VotesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_voteable, only: [:show, :edit, :update, :destroy]

  def create
    if same_user?
      flash[:error] = "You can't vote on your own posts"
    else
      @voteable.votes.create(user: current_user)
      flash[:notice] = "A successfully voted..."
    end

    redirect_to question_path(question)
  end

  def destroy
    @voteable.votes.where(user: current_user).take.try(:destroy)
    redirect_to question_path(question), notice: "Successfully removed vote..."
  end

  private

    def question
      @voteable.try(:question) || @voteable
    end

    def same_user?
      @voteable.user_id == current_user.id
    end
end

Dado que user_id está disponible tanto en Question como en Answer puedes utilizar @voteable.user_id sin tener la necesidad de revisar que tipo de voteable es.

2
  • Opté por este método, me parece más prácitco ya que se válida desde el create y no hay que manejar más instrucciones condicionales, alguna desventaja en cuanto a la otra solución? Commented el 31 oct. 2017 a las 22:35
  • @GarcíaHenry No, ninguna, solo es diferente en experincia de usuario, depende tus preferencias; claro que esta solución es más simple.
    – Gerry
    Commented el 31 oct. 2017 a las 22:53

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.