0

Ive got 3 models. Question, Answer and Result.

Got a middle model answers_results with an answer_id and a result_id.

The questions and answers are already in the database, so when someone starts a new survey it needs to save a result_id and answer_id in the answers_results table.

This is how my html looks like:

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

This is how my answer model looks like:

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

  belongs_to :question

  has_and_belongs_to_many :results, :join_table => :answers_results
end

and here is my Result model:

class Result < ActiveRecord::Base
  attr_accessible :animal_id

  has_and_belongs_to_many :answers, :join_table => :answers_results
end

Result controller:

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

But it doesnt save the answer_id to the answers_results. It does save the result_id.

So my question is: How do I save the answer_id to the answers_results table.

Thanks,,

Koop Otten
  • 429
  • 3
  • 12

1 Answers1

1

I thinks you have to use build method to store the answer_id directly in answer_results

Try the following approach

Get the answer with answer id and build result from that answer like below

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 
Raghuveer
  • 2,630
  • 3
  • 29
  • 59
  • I understand what you are trying to do. He cant find the Answer.find(params[:answer_id]). So i changed that to Answer.find(params[:id]). But that's not working. – Koop Otten Dec 13 '12 at 13:09
  • @KoopOtten are you passing answer_id as id to new/create action? If not passing pass it – Raghuveer Dec 13 '12 at 13:59
  • I tried to pass answer_id in to new action, but that doesnt work. It says 'could not find Answer without ID'. – Koop Otten Dec 13 '12 at 14:36