美文网首页
Rails6 中使用 Nested Form 嵌套表单

Rails6 中使用 Nested Form 嵌套表单

作者: 纸短情长4 | 来源:发表于2023-07-17 13:46 被阅读0次

1. 安装gem

Gemfile添加以下内容并运行 bundle install

gem 'nested_form', '~> 0.3.2'

2. 安装js插件

  yarn add jquery # 没有jquery的需要先安装jquery
  yarn add jquery_nested_form

在config/webpack/environment.js中添加以下引入代码:引入jquery

var webpack = require('webpack');
environment.plugins.append( 'Provide',
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
    })
)

在application.js 文件添加下面代码

  window.jQuery = jQuery
  window.$ = $
  require('jquery_nested_form')

3. 使用

例:假设有这样一个需求 一篇文章包含多个评论,需要在创建文章的同时创建多条评论

如何实现:

  1. 在 app/models/article.rb 文件添加以下代码
  has_many :comments
  accepts_nested_attributes_for :comments, allow_destroy: true 
  1. 在 app/views/articles/form.html.erb
    中 使用 nested_form_for 方法
  <%= nested_form_for article do |form| %>
    <%= form.fields_for :comments, :wrapper => false do |comment_form| %>
    <%= comment_form.text_area :content %>
    <%= comment_form.link_to_remove "Remove this comment" %>
   <% end %>
  <p><%= form.link_to_add "Add a comment", :comments %></p>
  <% end %>
  1. 在app/controllers/articles_controller.rb 中添加健壮参数
  params.require(:article).permit(:title, :content, comments_attributes: [:id, :content, :_destroy])

默认情况下link_to_add会在链接前添加元素内容。当使用列表这是不可取的。在这些情况下,“data-target”属性可用于指定新内容应插入的位置。

  <%= f.link_to_add "Add a comment", :comments, :data => { :target => "#comments" } %>

4. JavaScript事件

 // 限制元素
   $(function() {
  var fieldsCount,
      maxFieldsCount = 4,
      $addLink = $('a.add_nested_fields');

  function toggleAddLink() {
    $addLink.toggle(fieldsCount < maxFieldsCount)
  }

  $(document).on('nested:fieldAdded', function() {
    fieldsCount += 1;
    toggleAddLink();
  });

  $(document).on('nested:fieldRemoved', function() {
    fieldsCount -= 1;
    toggleAddLink();
  });  

  // count existing nested fields after page was loaded
  fieldsCount = $('form .fields').length;
  toggleAddLink();
})

相关文章

网友评论

      本文标题:Rails6 中使用 Nested Form 嵌套表单

      本文链接:https://www.haomeiwen.com/subject/rodgudtx.html