Jeff
Jeff

Reputation: 4003

Ruby Rails form

Hi there I'm extremely new to Ruby and I'm currently working with two models and two corresponding databases. A Quiz which has_many questions. And I'm trying to get the questions to show up in the quiz "edit view" here's what I have.

What currently is not working is the form entry for "questions" (see commented part below). I don't think I understand the expressions preceded by the colons very well. (e.g. :title, :quiz_date etc>) are they regular variables?

Anyway, the block of code in question successfully makes a form but using :questions it puts all the information from the questions row of the database into to the form filed (i.e id, question, answer, possible answers, etc). But it doesn't give me just the value of the question field.

But if I change it to :question (hoping to just get the value of the question field in the questions table) I get an error. I also tried :questions.question and just plain questions.question. None of these worked.

Any suggestions?

<%= form_for(@quiz) do |f| %>
<% if @quiz.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@quiz.errors.count, "error") %> prohibited this quiz from being saved:  </h2>

   <ul>
   <% @quiz.errors.full_messages.each do |msg| %>
     <li><%= msg %></li>
   <% end %>
   </ul>
  </div>
<% end %>

<div class="field">
  <%= f.label :title %><br />
  <%= f.text_field :title %>
</div>
<div class="field">
  <%= f.label :quiz_date %><br />
  <%= f.date_select :quiz_date %>
</div>
<div class="field">
  <%= f.label :reading %><br />
  <%= f.text_field :reading %>
</div>
<div>

  #the problem code
  <% @quiz.questions.each do |questions| %>
  <div class="question">
  <%= f.label :questions %><br />
  <%= f.text_field  %>
  </div>
  <% end %>
  #end problem code

</div>
<div class="actions">
 <%= f.submit %>
</div>
<% end %>

Upvotes: 0

Views: 77

Answers (1)

Kyle C
Kyle C

Reputation: 4097

You are going to need to adds accepts_nested_attributes in your Quiz model

Class Quiz < ActiveRecord::Base
 accepts_nested_attributes_for :questions

Then in your form add

   <%= f.fields_for :questions do |build| %>
    <div class="question">
     <%= build.label :questions %><br />
      <%= build.text_field :questions  %> #whatever attribute in your questions model
     <%end%>

You will find this Railscast very helpful, http://railscasts.com/episodes/196-nested-model-form-part-1

Upvotes: 3

Related Questions