0

In an edit.html.erb file I have the code

<%= form_for @submission do |f| %>
  <%= f.fields_for :submitted_answers do |answer| %>
     <%= answer.label :question_id %>
     <%= answer.number_field :question_id %>
  <% end %>
<% end %>

This shows me a number field that has the current value of question_id and allows me to change it. Now I just want to display that value and not let anyone change it. How would I get that value?

If I say

<% @question = :question_id %>

question just equals a string: "question_id"

Swiss
  • 1,260
  • 2
  • 17
  • 29

1 Answers1

3

You seem to be mistaking what's going on here. A symbol is an object that's similar to a string, but stored differently in memory and with a different syntax. When you pass a symbol to many methods in Ruby, they're used as references to methods. In this case, the :question_id symbol being passed as an argument to the number_field helper method, it's subsequently being called on the form object (that is, what is likely to be an ActiveRecord model).

Long story short, answer, a form builder, gets the question id from the model you passed into your form_for call. To display the value, you can do the same thing by calling the method directly, i.e.:

<%= @submission.question_id %>

However, since you're iterating over these using fields_for, you can instead get to the object the form builder is referencing by calling object:

<%= answer.object.question_id %>
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • My fault, I didn't really add the full context, basically answer is part of a nested attribute called submitted_answer. I am passing in submission, but every submission has multiple submitted_answers. – Swiss Nov 25 '12 at 05:56
  • @Swiss Right…I addressed that. – coreyward Nov 25 '12 at 05:58
  • Each submitted_answer has a different question_id, question_id isn't an attribute of submission. I also get undefined method `form_object' for # when I try to do the second part. – Swiss Nov 25 '12 at 06:00
  • Hey thanks, the line was actually <%= answer.object.question_id %>, but you got me on the right track. – Swiss Nov 25 '12 at 06:16
  • [coreyward](http://stackoverflow.com/users/203130/coreyward) thanks, you have helped me set the default value in my form collection_select element from the value stored in the database: [How to set the value in a collection_select from the database in the edit view](http://stackoverflow.com/questions/29145982/ror-how-to-set-the-value-in-a-collection-select-from-the-database-in-the-edit-v) – AOphagen Mar 20 '15 at 13:46