Accept a `child_index` lambda on `fields_for` with an argument
Created by: keegnotrub
Motivation / Background
While fields_for
currently accepts a lambda as an argument for child_index
, that lambda is called without any arguments. Being that we are enumerating the association on fields_for
at the time the lambda is called, we have an opportunity to pass the child of the association down to the lambda. This could simplify the case where you may want to use the id
of an Active Record object as the index. So with this change you could do something like this:
<%= author_form.fields_for :books, child_index: ->(book) { book.id } do |book_form| %>
<%= book_form.text_field :name %>
<% end %>
Prior to this, you would have had to enumerate the association yourself:
<% author.books.each do |book| %>
<%= author_form.fields_for :books, book, child_index: book.id do |book_form| %>
<%= book_form.text_field :name %>
<% end %>
<% end %>
Detail
Accepts passing the association's child as an argument in a lambda as the child_index
option in fields_for
.
Additional information
Used PR 19661 as a guide when passing a lambda to child_index
was originally introduced.
Checklist
Before submitting the PR make sure the following are checked:
-
This Pull Request is related to one change. Changes that are unrelated should be opened in separate PRs. -
Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
-
Tests are added or updated if you fix a bug or add a feature. -
CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.