我正在尝试关注此视频railscast #364,但我的嵌套路线遇到了很多麻烦。当我使用这段代码时:
<%= link_to "up", vote_movie_review_path(@movie, @reviews, type: "up"), method: "post" %>
我选择投票时收到此错误:
ActiveRecord::RecordNotFound in ReviewsController#vote
Couldn't find Review with 'id'=# <Review::ActiveRecord_Relation:0x007f0358c1e550>
这是我的路线:
vote_movie_review POST /movies/:movie_id/reviews/:id/vote(.:format) genre_linkers#vote
我创建了另一个未使用此代码嵌套的模型:
<%= link_to "up", vote_movie_path(movie, type: "up"), method: "post" %>
那个人工作了。所以我认为我的路径或者我如何调用这些对象都有问题。我几乎整天都在努力,我真的需要帮助。
review_controller.rb
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
before_action :set_movie
before_action :authenticate_user!
respond_to :html
def index
@reviews = Review.all
respond_with(@reviews)
end
def show
end
def vote
value = params[:type] == "up" ? 1 : -1
@review = Review.find(params[:id])
@review.add_evaluation(:vote, value, current_user)
redirect_to :back, notice: "thanks for the vote"
end
def new
@review = Review.new
respond_with(@review)
end
def edit
end
def create
@review = Review.new(review_params)
@review.user_id = current_user.id
@review.movie_id = @movie.id
if @review.save
redirect_to @movie
else
render 'new'
end
end
def update
@review.update(review_params)
respond_with(@review)
end
def destroy
@review.destroy
respond_with(@review)
end
private
def set_review
@review = Review.find(params[:id])
end
def set_movie
@movie = Movie.find(params[:movie_id])
end
def review_params
params.require(:review).permit(:genre, :description, :vote)
end
end
的routes.rb
Rails.application.routes.draw do
devise_for :users
resources :movies do
resources :reviews do
member { post :vote }
end
end
root 'movies#index'
end
和模型 的 review.rb
class Review < ActiveRecord::Base
belongs_to :user
belongs_to :movie
has_reputation :votes, source: :user, aggregated_by: :sum
end
答案 0 :(得分:1)
罪魁祸首是link_to:vote_movie_review_path(@movie, @reviews, type: "up")
的这一部分。 @reviews是一个ActiveRecord :: Relation而不是Review记录,因此找不到带ID的记录。