I’ve been reading my Agile Dev book over and over again, but I can’t
wrap my head around how to do this. There’s a question and answer
portion site of my site. You begin the process by adding a question to
the database. After that, the program should redirect you straight to
adding an answer for that question. The problem is, I don’t know how to
keep track of the answer’s question id.
Here’s what I have now:
####################### Controller
def new
@question = Question.new
end
def create
@question = Question.new(params[:question])
if @question.save
flash[:notice] = ‘Question was successfully created.’
redirect_to :action => ‘new_answer’, :id => @question
else
render :action => ‘new’
end
end
def new_answer
# the new answer must belong to a question… so I wasn’t sure
# whether to call it new answer or add answer.
@question = Question.find(params[:id])
@answer = Answer.new
@question.answers << @answer
end
def create_answer
@answer = Answer.new(params[:question_id])
if @answer.save
flash[:notice] = ‘Answer was added to the question.’
redirect_to :action => ‘show’, :id => @question
else
render :action => ‘create_answer’
end
end
###########################
########################### new_answer.rhtml
<%= start_form_tag :action => ‘create_answer’ %>
<%= render_partial ‘form_new_answer’ %>
<%= submit_tag “Create” %>
<%= end_form_tag %>
###########################
########################### _form_new_answer.rhtml
Answer to add
<%= text_area 'answer', 'answer', {:cols=>"80", :rows=>"5"} %>
########################### answer model
class Answer < ActiveRecord::Base
belongs_to :question
validates_presence_of :answer, :question_id
end
###########################
########################### question model
class Question < ActiveRecord::Base
validates_presence_of :question
has_many :answers
end
############################
Probably too much code for what you need to know…