【问题标题】:Rails cocoon nested form: webpacker can't find cocoonRails 茧嵌套形式:webpacker 找不到茧
【发布时间】:2020-08-19 00:02:03
【问题描述】:

我正在使用 cocoon gem 构建嵌套表单,因为我希望用户在“main_step”表单中填写任意数量的“sub_step”。

这是我的代码:

MainStep 模型

class MainStep < ApplicationRecord
    belongs_to :user
    has_many :sub_steps, inverse_of: :main_step
    accepts_nested_attributes_for :sub_steps, reject_if: :all_blank, allow_destroy: true
end

子步模型

class SubStep < ApplicationRecord
    belongs_to :main_step
end

sub_steps_controller

def index
    @sub_step = SubStep.new
    @main_step = current_user.main_step.last
end

def create
    # runs after I submit the form
end

sub_steps/index.html.erb

<%= form_for @main_step do |f| %>
     <%= f.fields_for @sub_step do |step| %>
         <%= render 'sub_step_fields', :f => step %>
     <% end %>
     <%= link_to_add_association 'Add', f, :sub_steps %>
     <% f.submit 'Confirm' %>
<% end %>

sub_steps/_sub_step_fields.html.erb

<div class='nested-fields'>
    <div class="field">
        <%= f.label :created_at %>
        <%= f.text_field :created_at %>
    </div>
    <%= link_to_remove_association "Remove", f %>
</div>

当我加载表单所在的页面时,单击“添加”按钮时没有任何反应。通过检查日志,我注意到 webpacker 找不到 cocoon gem,因此表单无法正常工作。

我使用的是 Rails 6.0.2,谢谢。

【问题讨论】:

    标签: ruby-on-rails webpacker cocoon-gem


    【解决方案1】:

    经过更多研究,我最终来到了这里:https://github.com/nathanvda/cocoon/pull/454

    对我有用的是:

    yarn add cocoon-js

    然后添加到我的application.js中

    import 'cocoon-js';

    【讨论】:

      【解决方案2】:

      命令yarn add cocoon-js从此源下载js包:

      https://www.npmjs.com/package/cocoon-js

      让 Cocoon 在 Rails 6+ 上工作:

      1. 宝石文件:

      gem 'cocoon'

      1. 控制台

      bundle

      yarn add cocoon-js

      1. 在 app/javascript/packs/application.js 中需要茧

      import "cocoon-js";

      附:这是一个带有香草js的替代新库https://www.npmjs.com/package/cocoon-js-vanilla

      【讨论】:

        猜你喜欢
        • 2018-08-17
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        • 2013-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        相关资源
        最近更新 更多