百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
N

nested_form_fields

> 编程语言
开源

在 Ruby on Rails 表单中动态添加和删除嵌套的 has_many 关联字段

306 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

在 Ruby on Rails 表单中动态添加和删除嵌套的 has_many 关联字段

Nested Form Fields

This Rails gem helps creating forms for models with nested has_many associations.

It uses jQuery to dynamically add and remove nested associations.

  • Works for arbitrarily deeply nested associations (tested up to 4 levels).
  • Works with form builders like simple_form.
  • Requires Ruby 1.9+ and the Rails asset pipeline.

Installation

Add this line to your application's Gemfile:

ruby
gem 'nested_form_fields'

And then execute:

bash
$ bundle

In your application.js file add:

javascript
//= require nested_form_fields

Rails 5.1+

You will need to install jQuery as Rails dropped it from its default stack.

Add to Gemfile:

ruby
gem 'jquery-rails'

Execute:

bash
$ bundle

Add to application.js:

javascript
//= require jquery3
//= require jquery_ujs

Usage

Assume you have a user model with nested videos:

ruby
class User ' }

Custom Fields Wrapper

You can change the type of the element wrapping the nested fields using the wrapper_tag option:

haml
= f.nested_fields_for :videos, wrapper_tag: :div do |ff|

The default wrapper element is a fieldset. To add legend element to the fieldset use:

haml
= f.nested_fields_for :videos, legend: "Video" do |ff|

You can pass options like you would to the content_tag method by nesting them in a :wrapper_options hash:

haml
= f.nested_fields_for :videos, wrapper_options: { class: 'row' } do |ff|

Rails 4 Parameter Whitelisting

If you are using Rails 4 remember to add {{ NESTED_MODEL }}_attributes and the attributes to the permitted params. If you want to destroy the nested model you should add :_destroy and :id. For example:

haml
# app/views/users/_form.haml.erb
= form_for @user do |f|
  = f.nested_fields_for :videos do |ff|
    = ff.remove_nested_fields_link
    = ff.text_field :video_title
    ..
  = f.add_nested_fields_link :videos
ruby
# app/controllers/users_controller
..
def user_params
    params.require(:user)
        .permit(:name,:email,videos_attributes:[:video_title,:_destroy,:id])
#                            ^^^                 ^^^           ^^^
#                            nested model attrs
#                                                             they will let you delete the nested model
end

Events

There are four JavaScript events firing before and after addition/removal of the fields in the nested_form_fields namespace:

  • fields_adding
  • fields_added
  • fields_removing
  • fields_removed

The events fields_added and fields_removed are triggered on the element being added or removed. The events bubble up so you can listen for them on any parent element. This makes it easy to add listeners when you have multiple nested_form_fields on the same page.

CoffeeScript samples:

coffeescript
# Listen on an element
initializeSortable -> ($el)
  $el.sortable(...)
  $el.on 'fields_added.nested_form_fields', (event, param) ->
    console.log event.target # The added field
    console.log $(this)      # $el

# Listen on document
$(document).on "fields_added.nested_form_fields", (event, param) ->
  switch param.object_class
    when "video"
      console.log "Video object added"
    else
      console.log "INFO: Fields were successfully added, callback not handled."

You can pass any additional data to the event's callback. This may be useful if you trigger them programmatically. Example:

coffeescript
# Trigger button click programmatically and pass an object `{hello: 'world'}`
$('.add_nested_fields_link').trigger('click', [{hello: 'world'}])

# Listen for the event
$(document).on "fields_added.nested_form_fields", (event, param) ->
  console.log param.additional_data #=> {hello: 'world'}

Index replacement string

Sometimes your code needs to know what index it has when it is instantiated onto the page. HTML data elements may need to point to other form elements for instance. This is needed for integration with rails3-jquery-autocomplete.

To enable string substitution with the current index use the magic string __nested_field_for_replace_with_index__.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Contributers

https://github.com/ncri/nested_form_fields/graphs/contributors

Issues· 22 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言