在我的应用程序中,我在用户和问题之间有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
&#13;
当我使用此链接运行程序时:http://127.0.0.1:3000/questions/1/answers/new:
我收到了这个错误:
未定义的方法`answers_path&#39;。
那么我的错误是什么?我知道我需要将answers_path更改为questions_answer路径但是如何做到这一点?
编辑:
我的路线:
Rails.application.routes.draw do
resources :questions do
resources :answers
end
end
&#13;
当我运行此链接时:http://127.0.0.1:3000/questions/1/answers
我收到了这个错误:&#39; nil&#39;不是与ActiveModel兼容的对象。它必须实现:to_partial_path。
答案 0 :(得分:0)
首先,在路线文件中,您声明您的答案资源都存在于父问题的范围内,但您只是在AnswersController#new
内进行建模 - 即便如此,{{1}您创建的对象与问题对象无关。
至少,您应该使用@answer
集合@answer
方法定义has_many
,以便将其定义为属于问题,例如:
build
您还应该调整其他控制器操作,以确保相应的答案操作始终作用于父问题资源。
您可能还需要调整@answer = @question.answers.build(user: current_user)
来电,以便Rails&#39;表单助手可以正确识别要为表单操作设置的控制器路径。您还需要提供嵌套资源的父级,以便响应者代码知道创建嵌套URL:
respond_with