【问题标题】:link_to_add_association and link_to_remove_association Nested form Cocoon gemlink_to_add_association 和 link_to_remove_association 嵌套形式 Cocoon gem
【发布时间】:2020-11-05 06:18:18
【问题描述】:

他是我第一次使用 cocoon gem,所以我不确定如何正确使用它,我没有收到错误但 link_to_add_association 不起作用。” link_to_remove_association”给出“未定义的方法 `new_record?'对于 nil:NilClass" 错误。当我点击 link_to_add_association 时,没有任何反应。 提前致谢。

_education_fields.html.erb

<div class="nested-fields">
  <div class="field">
    <%= f.label :institute_name %>
    <%= f.text_field :institute_name %>
  </div>

  <div class="field">
    <%= f.label :qualification %>
    <%= f.text_field :qualification %>
  </div>

  <div class="field">
    <%= f.label :specification %>
    <%= f.text_field :specification %>
  </div>

  <div class="field">
    <%= f.label :start_date %>
    <%= f.date_select :start_date %>
  </div>

  <div class="field">
    <%= f.label :end_date %>
    <%= f.date_select :end_date %>
  </div>

  <div class="field">
    <%= f.label :marks %>
    <%= f.text_field :marks %>
  </div>
   <%= link_to_remove_association "remove task", f, class: 'btn btn-primary btn-xs' %> 
</div>

_form.html.erb

<%= form_with(model: Education,url: user_educations_path, method: :post, local: true) do |form| %>
    <% if @user.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(@user.errors.count, "error") %> prohibited this education from being saved:</h2>
        <ul>
        <% @user.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>  
  <div class='user_educations'>
  <%= form.fields_for :educations do |education| %>
    <%= render 'education_fields', f: education %>
  <% end %>
  </div>
  <div class="actions">
    <%= form.submit %>
  </div>
  <div class="text-right">
        <%= link_to_add_association 'Add more', form, :educations %>
    </div>
<% end %>

用户.rb

class User < ApplicationRecord
  has_many :educations,dependent: :destroy
  accepts_nested_attributes_for :educations, reject_if: :all_blank, allow_destroy: true
end

【问题讨论】:

    标签: ruby-on-rails ruby forms nested-attributes cocoon-gem


    【解决方案1】:

    你的form_with命令有误,你应该提交一个实际的模型而不是类。

    一般人会这样写

    form_with(model: @education, ...
    

    并且@education 在控制器方法中设置。例如。像

    @education = Education.new 
    

    使用实例变量而不是写Education.new还允许我们使用相同的表单来创建新项目、渲染无效项目和编辑项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 2020-12-08
      • 1970-01-01
      相关资源
      最近更新 更多