繁体   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