skip to content

In Rails, what do accepts_nested_attributes_for's reject_if: :all_blank and limit: options do to an incoming questions_attributes payload?

level: middleimportance: should knowfreq 32%

answer

  1. reject_if takes a proc or symbol
  2. :all_blank ignores the _destroy key
  3. rejected hashes skipped silently
  4. limit: raises TooManyRecords
  5. limit: counts every hash, collections only

basics

~20 s

reject_if: :all_blank silently skips any child hash whose values are all blank, not counting _destroy, and a proc or method name can apply any rule. limit: caps how many hashes the writer accepts and raises NestedAttributes::TooManyRecords above it.

solid answer

~40 s

Both options guard the `questions_attributes=` writer. `reject_if:` takes a proc, a method name, or `:all_blank`, a built-in proc that rejects a hash when every value except `_destroy` is blank. A rejected hash is skipped silently: no record is built, no error is added. It also skips updates to existing questions, though `:all_blank` never rejects those because their `id` is not blank, and it never blocks a hash that `allow_destroy: true` will delete. `:all_blank` checks only the hash's own values, so a question with a blank prompt but a nested `choices_attributes` hash is kept. `limit:` takes a number, proc or method name and counts every hash, updates and deletions included; above it the writer raises `ActiveRecord::NestedAttributes::TooManyRecords` during assignment, so `update` raises instead of returning false. It applies to collections only.

code

ruby · 18 lines
ruby
class Survey < ApplicationRecord
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions,
    allow_destroy: true, reject_if: :all_blank, limit: 50
end

class Question < ApplicationRecord
  belongs_to :survey
  has_many :choices, dependent: :destroy
  accepts_nested_attributes_for :choices,
    reject_if: ->(attrs) { attrs["label"].blank? }
end

survey.questions_attributes = { "0" => { prompt: "", _destroy: "0" } }
survey.questions.size   # unchanged: the blank row was rejected

survey.questions_attributes = Array.new(51) { { prompt: "Q" } }
# => ActiveRecord::NestedAttributes::TooManyRecords

go deeper

for a junior

Recall that reject_if: :all_blank skips empty child rows without errors and that limit: raises when too many child hashes arrive.

for a middle

Explain the three forms of reject_if, why _destroy is ignored by :all_blank, and that limit: counts every hash and raises during assignment.

for a senior

Show you know the edges: nested hashes defeat :all_blank, silent rejection can hide user input, and TooManyRecords must be rescued.

for a principal

Separate payload guards from business rules: reject_if and limit: protect the writer, while validations and form objects own what users are told.

## Why the guards exist A survey-builder form typically renders a few empty question rows so the author can type new ones. When the form is submitted, every row arrives in `questions_attributes`, including rows nobody filled in. Left alone, each empty row would build a `Question` that then fails validation and blocks the save. And because the payload comes from the client, nothing stops it carrying thousands of hashes. `accepts_nested_attributes_for` has two options aimed at exactly these problems: `reject_if:` drops unwanted hashes, and `limit:` caps how many there may be. ## reject_if: in its three forms | Value | Rule applied to each hash | |---|---| | `:all_blank` | reject when every value, ignoring `_destroy`, is blank | | `proc { \|attrs\| attrs["prompt"].blank? }` | reject when the proc returns true | | `:skip_question?` | call that model method, with the hash if it takes an argument | `:all_blank` is shorthand for a built-in proc. A method given by symbol is called with the hash when it accepts one argument and without it when it takes none, so `reject_if: :new_record?` rejects every nested hash while the parent is still unsaved. ## What rejection means - **Silent.** A rejected hash builds nothing and adds no error. The user's input simply disappears, which is right for blank template rows and wrong for anything the user meant to send. - **Updates too.** The check also runs for hashes with an `id`: a rejected one leaves that existing question unchanged. `:all_blank` never rejects such a hash, though, because the `id` itself is a non-blank value. - **Deletes win.** A hash that `allow_destroy: true` will act on, with a truthy `_destroy`, bypasses `reject_if:` entirely. ## The :all_blank trap with nested children `:all_blank` looks only at the hash's own values. A question row with an empty prompt but a nested `choices_attributes` hash, even one whose choices are blank, has a non-empty hash among its values, and a non-empty hash is not blank. The row is kept, the question is built, and its blank prompt fails validation. For multi-level forms, write a proc that looks at the fields that matter, or let the child level reject its own blank rows and the parent check only its own columns. ## limit: 1. It accepts an integer, a proc, or a method name returning an integer. 2. It counts the whole collection of hashes in the payload, including updates and `_destroy` entries, before any of them is processed. 3. Above the limit, the writer raises `ActiveRecord::NestedAttributes::TooManyRecords` with a message stating the maximum and the count received. 4. The raise happens at assignment, so `survey.update(...)` raises rather than returning `false`, and the controller must rescue it if it wants a friendly response. 5. It applies to one-to-many associations only; on a one-to-one writer it is never checked. ## The order of the checks For a collection writer, the guards run in a fixed order, which explains most surprises: 1. The payload is normalised: a hash of hashes becomes a list of its values. 2. `limit:` is checked against the size of that list, before any hash is looked at. 3. Each hash with no `id` is skipped if `allow_destroy:` is on and `_destroy` is truthy, then skipped if `reject_if:` says so, and otherwise built. 4. Each hash with an `id` is matched against the survey's questions, raising `ActiveRecord::RecordNotFound` if it is not one of them, and then updated or marked unless `reject_if:` rejects it. Because the limit comes first, a payload that is too long fails even if most of its hashes would have been rejected as blank. ## Choosing between a guard and a validation - Use `reject_if:` for input that should never have been a record, such as empty template rows. - Use a validation on the child for input the user meant to send but got wrong; validation reports an error instead of discarding data. - Use `limit:` as a payload-size guard. A business rule such as "at most 50 questions per survey" belongs in a validation as well, because `limit:` counts one request's hashes rather than the questions already stored.

  • Why does survey.update raise rather than return false when the limit is exceeded?
    `limit:` is checked inside the `questions_attributes=` writer, which `update` calls while assigning attributes, before any validation. `TooManyRecords` is an exception, not a validation error, so it propagates out of `update` and rolls back its transaction.
  • When would you choose a reject_if proc over :all_blank?
    When some fields carry defaults or hidden values that are never blank, such as a position or a nested `choices_attributes` hash. `:all_blank` would then keep every row, so a proc naming the fields that matter, like `attrs["prompt"].blank?`, is the dependable rule.

  • reject_if: :all_blank adds a validation error for each blank row.
  • With limit: 20, Rails keeps the first 20 hashes and drops the rest.
  • limit: counts only new hashes, so updates and deletions are exempt.
  • reject_if can stop a child flagged _destroy from being deleted.
  • :all_blank looks inside nested choices_attributes hashes too.