我正试图用Rails中的form_with创建一个Edit操作。。。。我的其他CRUD操作正常,所以与我的表单有关。。。
<%= form_with(model: [@game, @review], local:true) do |form| %>
这是我试图创建的标签,但当我这样做时,我得到了这个错误
undefined method `review_path' for #<#<Class:0x00007fedfa8befd0>:0x00007fedfa8bd298>
Did you mean? view_paths
指引我回到标签,这是我的控制器
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except:[:index, :show]
before_action :correct_user, only: [:edit, :update, :destroy]
def index
@reviews = Review.all
end
def show
@review = Review.find(params[:id])
end
def new
@game = Game.find(params[:game_id])
@review = current_user.reviews.new
end
def edit
review = @game.reviews.find(params[:id])
end
def create
@review = current_user.reviews.new(review_params)
@game = Game.find(params[:game_id])
@review.game_id = @game.id
respond_to do |format|
if @review.save
format.html { redirect_to game_reviews_path(@review), notice: 'Review was successfully created.' }
format.json { render :show, status: :created, location: @review }
else
format.html { render :new }
format.json { render json: @review.errors, status: :unprocessable_entity }
end
end
end
def update
@review = current_user.reviews.update(review_params)
@game = Game.find(params[:game_id])
@review.game_id = @game.id
respond_to do |format|
if @review.update(review_params)
format.html { redirect_to @review, notice: 'Review was successfully updated.' }
format.json { render :show, status: :ok, location: @review }
else
format.html { render :edit }
format.json { render json: @review.errors, status: :unprocessable_entity }
end
end
end
def destroy
@review.destroy
respond_to do |format|
format.html { redirect_to game_reviews_path(@review), notice: 'Review was successfully destroyed.' }
format.json { head :no_content }
end
end
def correct_user
@review = current_user.reviews.find_by(id: params[:id])
redirect_to reviews_path, notice:" Not Authorized to Edit This Review" if @review.nil?
end
private
def set_review
@review = Review.find(params[:id])
end
def review_params
params.require(:review).permit(:reviewed_game, :rating, :game_id, :user_id)
end
end
我的路线。。。
devise_for :users
resources :game_studios
resources :games do
resources :reviews
end
root to: "games#index"
end
对Rails来说还是很新鲜的,任何帮助都会很棒!
感谢
def edit
end
private
def set_review
@game = Game.find params[:game_id] ####This is the key of fix
@review = Review.find(params[:id])
end
您没有在before_action
中初始化@game
实例所以当你打电话给<%= form_with(model: [@game, @review], local:true) do |form| %>
@game
为零,因此无法为此特定表单生成有效的路由。
因此,在编辑操作或before_action 中设置这个@game实例变量