Reputation: 704
I'm trying to implement a nested form in Padrino where I can add multiple instances of the child object using a Add whatever
button in the interface.
In Rails, one method to do this is to create a helper that generates nested fields everytime you click that Add whatever
button:
def link_to_add_fields( text, f, association, target )
new_object = f.object.class.reflect_on_association(association).klass.new
template_path = "#{association}/fields"
template = f.fields_for(association, new_object) do |builder|
render(template_path, :f => builder)
end
link_to text, "#", onclick: "add_#{association}_fields(this, \"#{escape_javascript(template)}\", \"#{target}\")"
end
However, when I try to do this in Padrino the f.fields_for (...)
block doesn't render to the template
variable, but instead is displayed in the layout.
I'm trying to find something like render_to_string
or similar in Padrino framework.
Anyone knows how to solve this? Thanks
Upvotes: 0
Views: 228
Reputation: 2255
It's not render
that's failing you, it's fields_for
. It erroneously detects that it's called from your erb template and concats to it.
Inherently it's true because you call link_to_add_fields from your erb, but at the time there is no detection method to guess this double dive from erb to ruby and back.
It can be considered a bug and you could create an issue here https://github.com/padrino/padrino-framework and provide a minimal failing project with a locked Gemfile.
As a solution I can suggest you manually switch your rendering engine to ruby and back like this:
def my_rendery_helper
@current_engine, engine_was = nil, @current_engine
template = fields_for(:moo) do |builder|
render('moo')
end
@current_engine = engine_was
template # now contains a SafeBuffer string
'result'
end
@current_engine
is a class variable that is used to detect rendering engine internally.
Upvotes: 1