Reputation: 121
I have a form as image below:
Then I want to render this partial from ajax call: from .js.erb
. But I don't know how to pass object to f from partial. See the image below:
how can I pass object to f:
Upvotes: 6
Views: 4153
Reputation: 341
you could send @journal
object then use fields_for @journal
into partial
.js.erb
$('.journal-entry').html("<%= j render partial: 'journal_entry_transaction_fields', object: @journal %>");
Partial .html.erb
<%= fields_for @journal do |f| %>
... code .....
<% end %>
Upvotes: 0
Reputation: 1659
I was pondering on how to replace part of the form (if that is what you are doing) for a while. The following is not perfect but "works for me".
We instantiate the form builder f in the controller (instead of a view) and render only your partial into a string. Then escape and render js into Ajax reply as usually.
def show
respond_to do |format|
format.js do
helpers.form_for(@journal) do |f|
out = render_to_string partial: 'journal_entry_transaction_fields', locals: {f: f}
render js: %($('.journal-entry').html("#{helpers.j out}");)
end
end
end
end
Perhaps the corresponding coffeescript part that is Turbolinks friendly and uses jQuery for sending Ajax is akin to
$(document).on 'change', '#something', (e) ->
$.get
url: "/path/to/your/controller/#{e.target.value}.js"
Upvotes: 2
Reputation: 6311
Adding :remote => true
it makes the button asynchronously(Ajax call).
index.html.erb
<%= link_to "Add Journal", new_journal_path, remote: true, class: 'new_journal_button'%>
new.js.erb
$('.new_journal_button').after("<%= j render('form') %>");
$('.new_journal_button').hide();
If you want to submit a form asynchronously(Ajax call)
_form.html.erb
<%= form_for(@journal, remote: true) do |f| %>
<div class="field">
<%= f.label "journal" %><br>
<%= f.text_field :title, placeholder: 'Journal', autofocus: true, 'data-behavior' => 'submit_on_enter' %>
</div>
<% end %>
Journals_controller.rb
def index
@journal = Journal.new
@journals = Journal.all
end
def create
@journal = Journal.new(journal_params)
respond_to do |format|
if @journal.save
format.html { redirect_to @journal, notice: 'Journal was successfully created.' }
format.js
else
format.html { render :new }
end
end
end
Upvotes: 2