如何在 Rails 中以嵌套形式省略现有子记录?
在我的应用程序中,用户有许多项目。我想创建一个“添加多个项目”表单,以便用户可以一次创建多个项目。
在我看来,最快的方法是制作一个用户表单,其中嵌套有项目字段,并省略用户字段。这样,当提交表单时,将保存用户并自动创建所有新的项目记录。
但是,我不希望现有项目显示在表单中。只有正在创建的新项目(来自@user.projects.build)的空字段。是否有我可以传递的参数或我可以在表单中更改的内容以省略现有的项目记录?
<% form_for (@user) do |f| %>
<% f.fields_for :project do |project_form| %>
<%= render :partial => 'project', :locals => {:f => project_form} %>
<% end %>
<%= add_child_link "New Project", f, :projects %>
<%= f.submit "save" %>
<%end%>
我正在使用 Ryan Bate 的复杂表单示例。该代码运行良好。我只是想忽略以这种形式显示的现有项目。
In my application an User has many Projects. I want to create a "add many projects" form, so the User can create many Projects at once.
It seemed to me that the quickest way was to make a User form with Project fields nested in it, and omit the User fields. This way when the form is submitted, the User is saved and all the new Project records are created automatically.
However, I don't want the existing Projects to show in the form. Only the empty fields for the new project that is being created (from @user.projects.build). Is there a parameter I can pass or something I can change in the form to omit the existing Project records?
<% form_for (@user) do |f| %>
<% f.fields_for :project do |project_form| %>
<%= render :partial => 'project', :locals => {:f => project_form} %>
<% end %>
<%= add_child_link "New Project", f, :projects %>
<%= f.submit "save" %>
<%end%>
I'm using the Ryan Bate's complex forms example. The code works fine. I just want to omit the existing projects from showing up in this form.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
new_record?
方法来区分新创建的记录和旧记录:You can use
new_record?
method to distinguish between newly created record and old one:您可以尝试
为一条记录提供空白字段。
在控制器中,您可以为关系生成多个记录,
这将创建五个与用户相关的新空项目,并且您当前的 fields_for 将包含新记录的字段。
You can try
that should give you blank fields for one record.
In the controller you can generate multiple records for the relationship
This will make five new empty projects related to the user and your current fields_for will have fields for new records.