views:

72

answers:

1

I have the following one to many associations. Document has many Sections and Section has many Items.

class Document < ActiveRecord::Base
  has_many :document_sections, :dependent => :destroy, :autosave => true
  has_many :document_items, :through => :document_sections
end

class DocumentSection < ActiveRecord::Base
  belongs_to :document
  has_many :document_items, :dependent => :destroy, :autosave => true
end

class DocumentItem < ActiveRecord::Base
  belongs_to :document_section
end

And the 'edit' action as follows :-

def edit
  @document = Document.find(params[:id])
end

Here is the edit.html.erb

<h1>Edit!</h1>

<% form_for(@document) do |f| %>
<%= f.error_messages %>

<p>
 <p> Header Comment <p/><br />
 <%= f.text_field :comment %>      
 <%= f.hidden_field :uid %>
</p>

<% @document.document_sections.each do |section| %>
 <% f.fields_for :section, :index => section.id  do |s| %>
  <p>
   <%= s.hidden_field :seqnum, options = {:value => section.seqnum} %>  
  </p>

  <% section.document_items.each do |item| %>
   <% s.fields_for :item, :index => item.id do |i| %>
      <p>
       <%= i.text_area :comments, options = {:value => item.comments} %> 
      </p>
   <% end %>
  <% end %>

 <% end %>
<% end %>
<p>
 <%= f.submit "Submit Comments" %>
</p>

<% end %>

I have to specify the options hash with the value attribute set, for eg:

options = {:value => item.comments} 

in order to show the item comments when I click the 'edit' link to modify the item comments. Shouldn't they be loaded by default, which seems to be the case for header comments.

Thanks for replying. Yes, i want to render the text area with the item.comments value from the database. The below code I had, does not load the comments.

<% s.fields_for :item, :index => item.id do |i| %>
 <p>
  <%= i.text_area :comments %> 
 </p>
<% end %>

can you explain me why

<%= text_area(:item, :comments) %> 

works but

<%= i.text_area :comments %> 

does not. Thanks much.

A: 

It seems your understanding of options is not correct. Here is what it is:

Additional options on the input tag can be passed as a hash with options

Which means that options sets attributes for the HTML tag.

You did not specify what exactly you want to do in the question, but I assume you want to render textarea tag with item.comments as a value. If so then you can use the 2nd parameter method (see the docs) and try this:

text_area(:item, :comments, :size => "20x30")
# => <textarea cols="20" rows="30" id="item_comments" name="item[comments]">
#      #{@item.comments}
#    </textarea>
Dmytrii Nagirniak