0

I followed the Getting Started With Rails tutorial to set up a simple blog with comments.

I went to apply it to my own scenario: histories with history items. Everything was more or less fine until I realized that I needed to have the ability to edit these history items (kind of like editing comments).

I've got it so there's an "Edit Item" link on the partial that displays the history items. It seems to hit the edit action in the history items controller. But I get a form with blank fields that says "Create" on the button.

Link from the partial that shows the history items:

<%= link_to 'Edit Item', edit_history_history_item_path(history_item.history, history_item) %>

The edit action in the history items controller:

def edit
  @history = History.find(params[:history_id])
  @history_item = HistoryItem.find(params[:id])
end

The part of the edit.html.rb page that references the partial:

<%= render 'form' %>

The partial itself:

<%= form_for([@history, @history.history_items.build]) do |f| %>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  (blah blah lots more fields)
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I've noticed the .build on the end of "@history.history_items" at the top of the partial. I assume this was required to make a new history item (or a new comment for a blog post) that references the originating history (or blog post). Is there some way I can keep that part for when it's a new history item, but do it another way when I want to edit an existing one?

Will Matheson
  • 338
  • 1
  • 4
  • 19

1 Answers1

2

You just need to make a small change to the partial (see below). You should pass in the history_item explicitly so that you don't have to depend on what instance variables are available to the partial:

<%= render 'form', history_item: @history_item %>

then:

<%= form_for([history_item.history, history_item]) do |f| %>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  (blah blah lots more fields)
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
RobHeaton
  • 1,390
  • 1
  • 9
  • 13
  • 1
    Thank you! Following on this, my call to include the add item partial became: `<%= render "history_items/form", history_item: @history.history_items.build %>` Also, I didn't have a plain show view for history items alone, so on the update action I brought in history from the history item and directed there - otherwise it's pretty much the same code as a blog post update in the original tutorial. – Will Matheson May 13 '13 at 17:08