Действует как голосующий voice_registered?

Я реализовал действия как голосующие в своем приложении Rails, и все идет хорошо.

Согласно его git: https://github.com/ryanto/acts_as_votable говорится, что существует метод, называемый голос_зарегистрирован? чтобы проверить, был ли голос действительным, если пользователь уже проголосовал за него ранее.

В нем говорится:

Чтобы проверить, был ли голос засчитан или зарегистрирован, используйте voice_registered? на вашу модель после голосования. Например:

@hat.liked_by @user

@hat.vote_registered? # => правда

Мне просто нужна помощь в попытке реализовать это.

Спасибо.

Я пробовал это в своем article_controller, но получаю ошибки от контроллера действий, такие как «Отсутствующие шаблоны статей/upvote, application/upvote with {:locale=>[:en], :formats=>[:html], :variants=>[] , :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}

def upvote
@article.upvote_by current_user
if @article.vote_registered?
  flash[:success] = "Successfully liked"
  respond_to do |format|
    format.html {redirect_to :back }
    format.json { render json: { count: @article.get_upvotes.size } }
  end
else
  flash[:danger] = "You have already liked this"
end
  end

Из моей статьи контроллер с текущим рабочим голосованием:

 def upvote
    @article.upvote_by current_user
    flash[:success] = "Successfully liked"
    respond_to do |format|
      format.html {redirect_to :back }
      format.json { render json: { count: @article.get_upvotes.size } }
    end
  end
  def downvote
    @article.downvote_by current_user
    flash[:success] = "Successfully disliked"
    respond_to do |format|
      format.html {redirect_to :back }
      format.json { render json: { count: @article.get_downvotes.size } }
    end
  end

Модель статьи:

class Article < ActiveRecord::Base
  validates :title, presence: true
  validates :body, presence: true

  belongs_to :user
  acts_as_votable
  has_many :comments, dependent: :destroy

  default_scope { order(created_at: :desc)}
end 

С веб-страницы при голосовании:

<h1 class="article-detail-title"><%= @article.title %></h1>
  <div class="votes" id="likes-dislikes">
      <hr>
    <%= link_to like_article_path(@article), method: :put, class: 'voting' do %>
      <i class="fa fa-thumbs-up"></i>
        <%= @article.get_upvotes.size %>
    <% end %>
    <%= link_to dislike_article_path(@article), method: :put, class: 'voting' do %>
      <i class="fa fa-thumbs-down"></i>
        <%= @article.get_downvotes.size %>
    <% end %>

    <div class="glyphicon glyphicon-calendar" id="article-date">
      <%= @article.created_at.strftime("%b %d, %Y") %>
    </div>
    <hr>
  </div>

Маршруты:

Rails.application.routes.draw do

  devise_for :users, :controllers => {registrations: "registrations", sessions: "sessions", :omniauth_callbacks => "callbacks"}
  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root to: 'articles#index'
  resources :articles do
    member do
      put "like", to: "articles#upvote"
      put "dislike", to: "articles#downvote"
    end
    resources :comments
  end
end

person Adam First    schedule 16.03.2016    source источник


Ответы (1)


Хорошо, я понял это. Я был близок, просто нужно было вернуть пользователя на существующую страницу.

def upvote
    @article.upvote_by current_user
    if @article.vote_registered?
      flash[:success] = "Successfully liked"
      respond_to do |format|
        format.html {redirect_to :back }
        format.json { render json: { count: @article.get_upvotes.size } }
      end
    else
      flash[:danger] = "You have already liked this"
      respond_to do |format|
        format.html {redirect_to :back }
      end
    end
  end
  def downvote
    @article.downvote_by current_user
    if @article.vote_registered?
      flash[:success] = "Successfully disliked"
      respond_to do |format|
        format.html {redirect_to :back }
        format.json { render json: { count: @article.get_downvotes.size } }
     end
    else
      flash[:danger] = "You have already disliked this"
      respond_to do |format|
        format.html {redirect_to :back }
      end
    end
  end
person Adam First    schedule 16.03.2016