0

Ive는 3 모델을 가지고 있습니다. 질문, 답변 및 결과.Cant는 answers_results로 답변을 얻습니다.

answer_id와 result_id가있는 중간 모델 answers_results가 있습니다.

질문과 답변이 이미 데이터베이스에 있으므로 누군가 새로운 설문 조사를 시작할 때 answers_results 테이블에 result_id와 answer_id를 저장해야합니다.

<input id="answer_id_5" name="answer_id[5]" type="checkbox" value="5"> 

내 대답 모델처럼 보이는 방법이있다 :

class Result < ActiveRecord::Base 
    attr_accessible :animal_id 

    has_and_belongs_to_many :answers, :join_table => :answers_results 
end 

결과 : 여기

class Answer < ActiveRecord::Base 
    attr_accessible :content, :question_id, :value 

    belongs_to :question 

    has_and_belongs_to_many :results, :join_table => :answers_results 
end 

과 내 결과 모델이다

이처럼 내 HTML을 모습입니다 제어기 :

class ResultsController < ApplicationController 

    def new 
    @result = Result.new 
    @animal = Animal.find(params[:id]) 
    end 

    def create 
    @result = Result.new(params[:result]) 
     if @result.save 
      redirect_to @result 
     else 
      render 'new' 
     end 
    end 

    def show 
    @result = Result.find(params[:id]) 
    end 
end 

하지만 answer_id를 answers_results에 저장하지 않습니다. result_id를 저장합니다.

내 질문은 : 어떻게 answer_id를 answers_results 테이블에 저장합니까?

감사합니다 ,, 난 당신이 응답 ID로 답을 얻기 다음 방법

을 시도 answer_results

에 직접 answer_id를 저장하는 빌드 방법을 사용하고 그 대답에서 결과를 구축 할 필요가 있다고 생각

+0

관련 컨트롤러 코드도 게시 할 수 있습니까? – RoryB

+0

결과 컨트롤러가 추가되었습니다! –

+0

컨트롤러 만들기 작업에서 응답을 사용하지 마십시오. –

답변

1

아래처럼

def new 
    answer = Answer.find(params[:answer_id]) 
    @result = answer.build_result # or anser.results.build 
    #this is based on has_one/has_many relationship between answer and results 
end 

def create 
@result = Result.new(params[:result]) 
if @result.save 
    redirect_to results_path 
else 
    render 'new' 
end 
end 
+0

나는 당신이하려는 것을 이해합니다. 그는 Answer.find (params [: answer_id])를 찾을 수 없습니다. 그래서 Answer.find (params [: id])로 변경했습니다. 그러나 그것은 작동하지 않습니다. –

+0

@KoopOtten이 (가) answer_id를 id로 new/create 작업에 전달하고 있습니까? 전달하지 않을 경우 – Raghuveer

+0

나는 새로운 액션에 answer_id를 전달하려고 시도했지만 그게 효과가 없습니다. 그것은 'ID없이 답변을 찾을 수 없습니다'라고 말합니다. –

관련 문제