I'm a bit new to rails/RhoMobile so I can't work out how to add a child object to a parent object so it's available as a member of the instance variable @questions on my form. Here is my controller method
def diary_day_one_morning
qgroup = "activity_day_one_morning"
@questions = Question.find(:all, :conditions => { { :name => "qgroup", :op => '=' } => qgroup } )
# make sure all questions have an answer
@questions.each do |q|
a = Answer.find(:all, :conditions => { { :name => "question_id", :op => '=' } => q.object }).first
if not a
a = Answer.new
a.question_id = q.object
a.save
end
#@questions[q].answer = a # here is my issue!!!
end
render :action => :diary_day_one_morning, :back => url_for(:action => :index)
end
At the @questions[q].answer part I'm a bit lost as to how to make my question joined to the answer. Then on the form how do I refer to the answer? Here is what I already have:
<% @questions.each_with_index do |question, qcount| %>
<div class="ui-block-a">
<div class="ui-bar ui-bar-e">
<%= question.qpromptshort %>
</div>
</div>
<% a = Answer.find(:all, :conditions => { { :name => "question_id", :op => '=' } => question.object }).first %>
<% if a %>
<input type="hidden" id="answer<%=qcount%>[object]" name="answer<%=qcount%>[object]" value="<%=a.object%>" />
<div class="ui-block-b">
<input type="text" id="answer<%=qcount%>[value1]" name="answer<%=qcount%>[value1]" value="<%=a.value1%>" />
</div>
.......
I'd prefer to refer to the answer (a) as a member of the question instead of looking it up.
You can get the index of each object in the @questions array by using the each_with_index method.
@questions.each_with_index do |q,qindex|
a = Answer.find(:all, :conditions => { { :name => "question_id", :op => '=' } => q.object }).first
if not a
a = Answer.new
a.question_id = q.object
a.save
end
# use qindex to add it back into the @questions array
@questions[qindex].answer = a
end
Then in the page the answer will be available as question.answer.