Search code examples
ruby-on-railsrubyrender-to-string

Rails render_to_string with partial that requires a form builder object?


I feel like this is something simple and I'm completely missing it..

I have an edit.html.erb file that has something akin to this in it;

<%= form_for @some_object, html: { autocomplete: "off" } do |f| %>
  <%= render 'form', f: f %>
<% end %>

the _form.html.erb file it is referencing has something akin to this in it;

<%= f.fields_for :some_nested_object, @some_object.some_nested_object.order(:sort_order) do |obj| %>
    foobarbaz form stuff..
<% end %>

I can't change the edit or the form partial. They are required as is by a large portion of the site.. it is what it is, and I'm stuck with that.

I want to be able to render the form partial with the f.fields_for to string in a json result.

def index
  respond_to do |format|
    format.json { render json: { html: render_to_string('/path/to/_form.html.erb',
                                                        layout: false,
                                                        locals: { f: ????????? }
  end
end

But, I am not sure how to assign f in this case.

I feel like it should be something akin to

locals: { f: ActionView::Helpers::FormHelper::form_for(@some_object) }

or something like that but that obviously doesn't work.

This feels like this should be simple, and I'm just an idiot..

Thoughts? (about the question, not my being an idiot =)


Solution

  • Ok, behold the hacky hack:

    def index
      respond_to do |format|
    
        format.json do
          form_builder = view_context.form_for(@some_object) { |builder| break builder }
    
          html = render_to_string(
            '/path/to/_form.html.erb',
            layout: false,
            locals: { f: form_builder }
          )
          render json: { html: html } 
        end
      end
    end
    

    That being answered (assuming it's actually working) note that this is a hack. This is not a way we should be writing code (even though we sometimes have to) and the next step is to figure out why are we in the situation when we have to do such a hackery.

    For example, is there any chance you are re-inventing cocoon gem?