Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

edit - Rails: Use same partial for creating and editing nested items

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...