将新的父对象标识传递给link_to

时间:2017-10-16 09:02:42

标签: ruby-on-rails

我正在尝试使用accepts_nested_attributes_for

同时保存父对象和子对象

控制器新方法中的代码:

def new
  @project = Project.new
  @project.instances.build
end

和表单看起来像这样:

<%= simple_form_for(@project) do |f| %>
  <%= f.input :name %>
  <%= link_to "Add New Instance", new_project_instance_path(@project), id: "new_link", remote: true %>
<% end %>

此路线条目是:

resources :projects do
  resources :instances
end 

需要显示的字段instances/_form.html.erb

<%= form.simple_fields_for :instances do |i| %>
  <%= i.input :user_id %>
  <%= i.input :password %>
  <%= i.input :service_url %>  
<% end %>

此处project_id的问题是:nil,它给出错误:

No route matches {:action=>"new", :controller=>"instances", :project_id=>nil} missing required keys: [:project_id]

我需要以某种方式调用<%= render 'cdd_instances/form', form: f %>,以便在项目详细信息下方呈现字段,我该如何实现?

2 个答案:

答案 0 :(得分:0)

我认为你的@project为null,你必须传递:

 new_project_instance_path(project_id: (@project || ''))

答案 1 :(得分:0)

在这种情况下,您无法通过非持久@project来创建此link_to网址。

我相信你正在寻找类似的东西:cocoon

<%= simple_form_for @project do |f| %>
  <%= f.input :name %>
  <h3>Instances</h3>
  <div id="instances">
    <%= f.simple_fields_for :instances do |instance| %>
      <%= render 'instance_fields', f: instance %>
    <% end %>
    <div class="links">
      <%= link_to_add_association 'add instance', f, :instances %>
    </div>
  </div>
  <%= f.submit %>
<% end %>

干杯!