簡體   English   中英

Ruby on Rails中的路徑和控制器錯誤

[英]Error with path and Controller in Ruby on Rails

在我的應用程序中,我與用戶和問題之間存在1-n關系,與問答之間存在1-n關系,而用戶與問題之間存在1-n關系。
我的路線:

  question_answers GET /questions/:question_id/answers(.:format) answers#index POST /questions/:question_id/answers(.:format) answers#create new_question_answer GET /questions/:question_id/answers/new(.:format) answers#new edit_question_answer GET /questions/:question_id/answers/:id/edit(.:format) answers#edit question_answer GET /questions/:question_id/answers/:id(.:format) answers#show PATCH /questions/:question_id/answers/:id(.:format) answers#update PUT /questions/:question_id/answers/:id(.:format) answers#update DELETE /questions/:question_id/answers/:id(.:format) answers#destroy 

我的控制器:

 class AnswersController < ApplicationController before_action :authenticate_user!,only: [:edit,:update,:destroy,:new,:create] before_action :set_answer, only: [:show, :edit, :update, :destroy] respond_to :html def index @answers = Answer.paginate(page: params[:page]) #@answers = Answer.all respond_with(@answers) end def show respond_with(@answer) end def new @questions=Question.find params[:question_id] @answer = Answer.new user: current_user respond_with(@answer) end def create @answer = Answer.new(answer_params) @answer.save respond_with(@answer) end end 

當我使用此鏈接運行程序時: http : //127.0.0.1 : 3000/questions /1/ answers/new
我收到此錯誤:未定義的方法“ answers_path”。 那么我的錯誤是什么?我需要將answer_path更改為questions_answer路徑,但是該怎么做呢?
編輯:我的路線:

 Rails.application.routes.draw do resources :questions do resources :answers end end 

當我運行此鏈接時: http : //127.0.0.1 : 3000/questions/1/answers
我收到此錯誤:“ nil”不是與ActiveModel兼容的對象。 它必須實現:to_partial_path。

首先,在路由文件中,您聲明所有答案資源都位於父問題的范圍內,但您僅在AnswersController#newAnswersController#new建模–即使如此,您創建的@answer對象也沒有任何關系。到問題對象。

至少,您應該使用has_many集合的build方法定義@answer ,以便將其定義為屬於問題,例如:

@answer = @question.answers.build(user: current_user)

您還應該調整其他控制器操作,以確保適當的答案操作始終在父問題資源的范圍內。

您可能還需要調整您的respond_with調用,以便Rails的表單助手可以正確識別要為表單操作設置的控制器路徑。 您還需要提供嵌套資源的父級,以便響應者代碼知道創建嵌套URL:

respond_with(@question, @answer)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM