【问题标题】:Rails: Use same partial for creating and editing nested itemsRails:使用相同的部分创建和编辑嵌套项
【发布时间】:2013-05-13 16:04:47
【问题描述】:

我跟着Getting Started With Rails tutorial用cmets建立了一个简单的博客。

我把它应用到我自己的场景中:带有历史项目的历史。在我意识到我需要能够编辑这些历史项目(有点像编辑 cmets)之前,一切都或多或少地好。

我知道了,所以在显示历史项目的部分上有一个“编辑项目”链接。它似乎命中了历史项目控制器中的编辑操作。但我得到一个带有空白字段的表单,按钮上写着“创建”。

显示历史项目的部分链接:

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

历史项目控制器中的编辑操作:

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

edit.html.rb 页面中引用部分的部分:

<%= render 'form' %>

部分本身:

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

我注意到部分顶部“@history.history_items”末尾的 .build。我认为这是创建引用原始历史记录(或博客文章)的新历史记录项(或博客文章的新评论)所必需的。当它是一个新的历史项目时,我有什么方法可以保留该部分,但当我想编辑现有的项目时,可以用另一种方式吗?

【问题讨论】:

    标签: ruby-on-rails edit nested-forms partial


    【解决方案1】:

    您只需要对部分进行一些小改动(见下文)。您应该显式传入 history_item,这样您就不必依赖于部分可用的实例变量:

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

    然后:

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

    【讨论】:

    • 谢谢!在此之后,我对添加部分添加项目的调用变为:&lt;%= render "history_items/form", history_item: @history.history_items.build %&gt; 另外,我没有单独的历史项目的简单显示视图,所以我从历史项目中引入历史并指向那里的更新操作 -否则它与原始教程中的博客文章更新几乎相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    相关资源
    最近更新 更多