【发布时间】:2015-05-08 20:36:03
【问题描述】:
我熟悉如何在 Rails 4 中获得典型的nested_attributes 表单。但是我正在尝试在views/people/show.html.erb 模板上创建一个仅用于其中一个嵌套属性的表单我的 Person 模型。
class Person
has_many :histories
accepts_nested_attributes_for :histories
end
class History
belongs_to :person
end
查看
<% @person.histories.each do |history| %>
<% if history.created_at != nil %>
<p>Date: <%= history.created_at.strftime("%a, %b %e %Y") %></p>
<p>Visit Summary: <%= history.visit_summary %></p>
<% else %>
<p>N/A</p>
<% end %>
<% end %>
<%= form_for @person do |p| %>
<%= p.fields_for :histories do |history| %>
<%= history.label :visit_summary %>
<%= history.text_area :visit_summary %>
<% end %>
<%= p.submit 'Create History Item' %>
<% end %>
我知道我犯了一些严重的视图逻辑错误,但我基本上试图用这个表单完成的是当一个人导航到 /persons/:id 时,他们会看到这个人的摘要,包括与该人相关的历史。他们还有一个表单,用于将单个历史记录项添加到个人历史记录集合中。
现在,为了让表单显示在视图中,我必须像这样编辑我的控制器:
class PeopleController < ApplicationController
...
def show
@person = Person.find(person_params)
@person.histories.build
end
end
但是,调用 histories.build 会创建一个对象,该对象最终会显示在视图中的历史项目列表中,即使它尚未持久化到数据库中,因此我的逻辑是排除其 created_at 的历史项目属性为零。此外,当我提交历史项目并被重定向到 /people/:id 时,我会看到两个表单字段;一个用于编辑我以前创建的历史记录项,另一个用于创建新的历史记录项。我只希望在任何给定时间都存在一个空表单字段。
我的问题是:
1.) 我怎样才能为我的人物模型上的关联制作一个小的、单一的属性表单以显示在 show.html.erb 模板中?
2.) 是否使用nested_attributes 形式来解决它?
3.) 是否可以提供在线文档来说明如何创建这些小型自定义表单?
非常感谢!
【问题讨论】:
标签: ruby-on-rails forms