Rails: Use same partial for creating and editing nested items

我的梦境 提交于 2019-12-25 04:14:52

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/16526452/rails-use-same-partial-for-creating-and-editing-nested-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!