Действует как голосовые рельсы ActiveRecord::RecordNotFound и NoMethodError в ArticlesController
Я закончил курс Udemy по созданию блогового приложения в Rails. Я добавил функциональность JSON для мобильного просмотра статей и регистрации / входа. Все работает.
Моя следующая проблема - я хочу добавить отрицательные и отрицательные голоса, чтобы зарегистрированные пользователи могли голосовать за статьи.
Я установил гем act_as_votable и следовал пошаговой инструкции ( http://www.mattmorgante.com/technology/votable), как его реализовать, но я получаю следующие ошибки, когда пользователь нажимает на upvote/downvote: ActiveRecord::RecordNotFound или NoMethodError в ArticlesController
Я предполагаю, что первая ошибка в том, что контроллер статьи уже знает, о какой статье я говорю, когда нажимаю upvote? Поэтому я прокомментировал это для downvote_by, и он не знает метод downvote_by
Что я пропустил? Ценю помощь. Благодарю.
Если я нажму Upvote:
Контроллер статей:
class ArticlesController < ApplicationController
before_action :authenticate_user!, :except => [:index, :show]
before_filter :set_article, only: [:show, :edit, :update, :destroy]
def index
@articles = Article.all
end
def new
@article = Article.new
end
def create
@article = current_user.articles.build(article_params)
if @article.save
flash[:success] = "Article has been created"
redirect_to articles_path
else
flash.now[:danger] = "Article has not been created"
render :new
end
end
def edit
if @article.user != current_user
flash[:danger] = "You can only edit your own article"
redirect_to root_path
end
end
def update
if @article.user != current_user
flash[:danger] = "You can only edit your own article"
redirect_to root_path
else
if @article.update(article_params)
flash[:success] = "Article has been updated"
redirect_to @article
else
flash.now[:danger] = "Article has not been updated"
render :edit
end
end
end
def show
@comment = @article.comments.build
end
def destroy
if @article.destroy
flash[:success] = "Article has been deleted"
redirect_to articles_path
end
end
def upvote
@article=Article.find(params[:id])
@article.upvote_by current_user
flash[:success] = "Successfully liked"
respond_to do |format|
format.html {redirect_to articles_path }
format.json { render json: { count: @article.liked_count } }
end
end
def downvote
#@article = Article.find(params[:id])
@article.downvote_by current_user
flash[:success] = "Successfully disliked"
respond_to do |format|
format.html {redirect_to articles_path }
format.json { render json: { count: @article.disliked_count } }
end
end
private
def article_params
params.require(:article).permit(:title, :body)
end
def set_article
@article=Article.find(params[:id])
end
end
Файл show.html.erb, который относится к лайкам / дислайкам:
<div class="article-body">
<%= link_to article_like_path(@article), method: :put do %>
Upvote
<%= @article.get_upvotes.size %>
<% end %>
<%= link_to article_dislike_path(@article), method: :put do %>
Downvote
<%= @article.get_downvotes.size %>
<% 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
файл маршрутов:
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".
#namespace :api, defaults: {format: :json} do
# scope :v1 do
# mount_devise_token_auth_for 'User', at: 'auth', skip: [:omniauth_callbacks]
# :controllers => { :sessions => "api/v1/sessions" },
# end
#end
# You can have the root of your site routed with "root"
root to: 'articles#index'
resources :articles do
put "like", to: "articles#upvote"
put "dislike", to: "articles#downvote"
resources :comments
end
end
1 ответ
Удалить эту строку кода из upvote
а также downvote
действия в вашем контроллере:
@article = Article.find(params[:id])
смотреть пробелы между знаком равенства
Отредактируйте свой before_filter
к этому:
before_action :set_article, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
Ваши маршруты должны быть:
resources :articles do
member do
put "like", to: "articles#upvote"
put "dislike", to: "articles#downvote"
end
resources :comments
end