Know what errors lurk in your code? Rollbar detects and alerts you when code breaks in production. Get the stack trace, code, and data to help you d̶e̶b̶u̶g̶ defeat Ruby errors. Learn more.

RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

A cleaner alternative to accepts_nested_attributes_for

Redtape provides an alternative to ActiveRecord::NestedAttributes#accepts_nested_attributes_for in the form of, well, a Form! The initial implementation was heavily inspired by “7 Ways to Decompose Fat Activerecord Models” by Bryan Helmkamp.

Comments

Really like the look of this. It is similar to something I have been thinking about for a while. Could this object do more than just assist in nested objects? A few thoughts:

Would love for it to have a default implementation of populate for simple non-nested objects. This would just create an instance of the object being saved/validated and assign each accessor. Kind of an alternative to attr_protected or the new strong attributes.

Would be nice if validation could also be placed at this form level. This way validations at the object level could apply site-wide, but you could layer additional validation on a per-form basis. Would be nice for multi-page forms or having stricter requirements in certain setups (maybe admin screens have less validation than end user screens).

Eric: I’ve considered this. My concern is that, quickly, redtape begins to overlap with other gems such as Inherited Resources.

I didn’t document it but validations can be placed in the form. However, I’d strenuously recommend against using them for anything but fields that do not map directly onto a model’s field. Otherwise, the form validation begins to overlap responsibilities with the model’s validations.

Good thoughts, though. I’ve barked up similar trees already.

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in