niiru
niiru

Reputation: 5112

Nested Forms - fields_for() and symbols

I've been struggling with this for the last several hours:

I have a nested form (shown below) and it's working, but for the life of me, I cannot figure how to access the :student_id in the _form_outcome_ratings.html.erb. It displays the appropriate student_id in the hidden field that's created, but I have no idea how to access that number to display the student's name next to the rating field. When I try to reference :student_id or :student_id.to_s it returns "student_id" instead of the number. I think I'm missing or misunderstanding something very basic, but I can't figure out what!

Thank you for taking the time to look at this, and let me know if there's anything I need to clarify or add.

/app/views/learning_outcomes/_form_rate.html.erb

<% form_for(@learning_outcome) do |f| %>  
  <% f.fields_for :outcome_ratings do |g| %>  
    <%= render :partial => 'form_outcome_ratings', :locals => {:f => g} %>  
  <% end %>  
  <%= f.submit %>  
<% end %>  

/app/views/learning_outcomes/_form_outcome_ratings.html.erb

<%= f.hidden_field :student_id %>  
<%= f.label :rating %><%= f.text_field :rating %>  

/app/controllers/learning_outcomes_controller.rb

def rate
  @learning_outcome = LearningOutcome.find(params[:id], :include => {:section => {:students => {:outcome_ratings => [:learning_outcome, :student]}}})
  @learning_outcome.section.students.each do |student|
    @learning_outcome.outcome_ratings.build(:student_id => student.id) if student.outcome_ratings.where(:learning_outcome_id => @learning_outcome.id).blank?
  end    
end

Upvotes: 1

Views: 402

Answers (1)

apneadiving
apneadiving

Reputation: 115511

Not sure I understod what you want, but...

You can access all variables of a model within a form builder if you do as follows:

f.object.your_variable

example:

f.object.id

Upvotes: 2

Related Questions