0

I'm trying to DRY up one of my forms that sometimes has additional fields (for nested models) when making a new entry, but wouldn't need those fields when performing an update. As such, I was trying to pass the additional fields in via a block, but the form object isn't being passed properly.

Is there a way to pass a form object (or really any variable) into a yield?

Example code for reference:

_form.slim

= nested_form_for @model do |f|
  .row
    = f.label :name
    = f.text_field :name, autofocus: true
  ...
  = yield
  ...
  = f.submit 'Save'

new.html.slim

== render layout: 'model/form' do
  h3 Additional Fields
  = f.fields_for :nested do |h|
      = a.label :name, 'Nested Name'
      = a.text_field :name
      = a.link_to_remove do
        = fa_icon 'times-circle-o'
  = f.link_to_add "Add another nested model", :nested

edit.html.slim

== render layout: 'model/form'
Jonathan Bender
  • 1,911
  • 4
  • 22
  • 39
  • I'm a bit confused, why are you rendering layouts _within_ your views? Shouldn't you be rendering partials instead? – Christian Feb 17 '14 at 03:43
  • I started off trying to do it using partials initially, but it wasn't working, so I tried to follow this post: http://stackoverflow.com/questions/2951105/rails-render-partial-with-block – Jonathan Bender Feb 17 '14 at 03:48
  • Hmm, that question is 4 years old, I'm not sure if that would actually work anymore. Personally, I'd just use partials, and pass in a local variable like `additional_fields`, then in the form partial do a conditional and only display additional fields when `additional_fields` is true. – Christian Feb 17 '14 at 03:59

1 Answers1

1

To elaborate on my comment, this is how I'd do it using partials:

_form.slim

= nested_form_for @model do |f|
  .row
    = f.label :name
    = f.text_field :name, autofocus: true

  ...

  - if defined?(additional_fields)
    h3 Additional Fields
      = f.fields_for :nested do |h|
          = a.label :name, 'Nested Name'
          = a.text_field :name
          = a.link_to_remove do
            = fa_icon 'times-circle-o'
      = f.link_to_add "Add another nested model", :nested

  ...

  = f.submit 'Save'

new.html.slim

  == render 'model/form', :additional_fields => true

edit.html.slim

  == render 'model/form'

I might be missing something, but I'm not sure why this wouldn't work.

Christian
  • 19,605
  • 3
  • 54
  • 70