Rendering edit form via ajax - ruby-on-rails

I am attempting to render a form via ajax. It works fine for creating a new venue, but when attempting to edit an existing venue the venue data should load into the form. The form (_modal) is rendered when the edit venue link is called, however the form is processed as a new form, with all fields blank. Calling #venue at the binding.pry, we see the correct venue object.
How would I get the form to process as edit rather than new? Ideas:
respond_to do |format|
format.js { *do stuff* }
Add more parameters to form?
Do it manually - change form attributes and/or fill in data with jquery
Appreciate any suggestions!
_modal.html.erb:
<section id="venue-modal" class='modal' title="Venue Form" class="">
<%= simple_form_for(#venue, remote: true) do |v| %>
<div id='closeButton'><a href='#'>x</a></div>
<% binding.pry %>
<%= v.input :name, label: "Venue Name" %>
<%= v.input :city %>
<%= v.input :state, collection: States.us_states %>
<div class="actions">
<%= v.submit 'Submit', class: 'button' %>
</div>
<% end %>
</section>
Renders following html:
<form accept-charset="UTF-8" action="/venues" class="simple_form new_venue" data-remote="true" id="new_venue" method="post">
Link calling the modal:
<%= link_to edit_venue_path(venue), :remote => true, :class => "edit_venue_link" do %>
Controller:
def edit
id = params[:id]
if id == 'new'
#venue = Venue.new
else
#venue = Venue.find(id)
end
end
Venue.js:
$('.edit_venue_link').on("ajax:success", function(e, data, status, xhr) {
// stuff happens

Replace the modal content with this line of code in modal.js.erb:
$('#venue-modal').html("<%= escape_javascript(render partial: 'venues/modal') %>");
Controller:
def edit
id = params[:id]
if id == 'new'
#venue = Venue.new
else
#venue = Venue.find(id)
end
respond_to do |format|
format.js { render 'venues/modal' }
end
end
Section tags moved out of the modal partial. The form then recognizes #venue and the fields load appropriately.

Related

Rails AJAX link_to not refreshed controller action

In my Rails 5 app, Doctor/Admin have to create a Caregiver with linked Patient (new object CaregiverPatient represents that). During this process, inside the registrants_controller#new, Doctor/Admin search for a Patient (which is done by Ransack gem) and from the result he/she push Add Patient button to add Patient to initialized CaregiverPatient object from caregiver_patient#new and display #patient.full_name inside the form.
In order not to lose already filled form fields, everything must be done asynchronously. I've tried to do so with AJAX, below my code:
registrant_controller.rb
def new
#registrant = Registrant.new
#patient = Registrant.find(session[:patient_id_to_add_caregiver]) if session[:patient_id_to_add_caregiver]
end
registrants/_new_form.html.erb
<%= form_for #registrant do |f| %>
<%= f.fields_for :registration do |registration| %>
<% if #patient %>
<div id="add-patient"></div>
<% else %>
<%= required_text_field_group registration, #registrant, :registrant_id, "Patient Added", {}, { disabled: true } %>
<% end %>
<% end %>
# some other logic (...)
# patient search result
<% #registrants do |registrant| %>
<%= link_to 'Add Patient', new_registrant_link_path(registrant), remote: true %>
<% end %>
Add Patient button triggers caregiver_patients#new action:
#caregiver_patient_controller.rb
class CaregiverPatientsController < ApplicationController
# new_registrant_link_path
def new
session[:patient_id_to_add_caregiver] = params[:registrant_id].to_i
respond_to do |format|
format.html { redirect_to request.referer }
format.js { render action: 'patient_to_caregiver', notice: 'Patient Added' }
end
end
end
AJAX request is made:
#views/caregiver_patients/patient_to_caregiver.js.erb
$("#add-patient").html("<%= escape_javascript(render :partial => 'registrants/add_patient') %>");
views/registrants/_add_patient.html.erb
Patient Added: <%= #patient.full_name %>
But surprisingly gets an error:
ActionView::Template::Error (undefined method `full_name' for nil:NilClass):
1: Patient Added: <%= #patient.full_name %>
Which probably means that registrants_controller#new was not refreshed under the hood somehow. What have I missed?

Link_to remote:true not rendering a partial

Trying to get a flash message and render a partial on an ajax call with link_to and remote:true
I have in my controller examples.rb:
def create
* Some stuff happens *
respond_to do |format|
format.js
format.html do
flash[:notice] = "Works!"
redirect_back(fallback_location: root_path)
end
end
end
I have the "link_to" form in _one_partial.html.erb
<%= link_to examples_path(whatever: locals[:whatever]), class: "whatever", method: :post, remote: true do %>
<div class="whatever_vix">
<p> Click Here! </p>
</div>
<% end %>
which is in a view as:
<div id="addhere">
<%= render 'favorites/one_partial', locals: {whatever: #whatever} %>
</div>
and in create.js.erb
$('#addhere').append("<%= j render 'whatever/another_partial' %>")
The ** some stuff happens ** part in my controller obviously works, but the new partial in create.js.erb doesn't show, neither the flash message appears once I add remote:true to the "link_to" form

AJAX partial in loop

I am trying to render a partial with ajax when submitting a form.
Here is my code:
index.html.erb
<% #inbox.each do |conversation| %>
<div class="message">
<div id="messages">
<%= render conversation.messages %>
</div>
<div class="inner-message">
<%= form_tag({controller: "conversations", action: "reply", id: conversation.id}, {remote: true, method: :post}) do %>
<%= hidden_field_tag :recipient_id, current_user.id %>
<%= hidden_field_tag :subject, "#{current_user.name}" %>
<div class="form-group">
<%= text_area_tag :body, nil, class: "form-control", placeholder: "Odgovori" %>
</div>
<div class="form-group">
<%= submit_tag 'PoĊĦlji', class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
<% end %>
index.js.erb
$("#messages").html("<%= escape_javascript(render conversation.messages) %>")
conversations_controller.rb
def reply
conversation = current_user.mailbox.conversations.find(params[:id])
current_user.reply_to_conversation(conversation, params[:body])
respond_to do |format|
format.html { redirect_to messages_path }
format.js { redirect_to messages_path }
end
end
when I submit the form, I get an undefined local variable error:
ActionView::Template::Error (undefined local variable or method
`conversation' for #<#:0x007fd287172fa8>)
How do I pass the local variable from the loop to the .js.erb view?
Thanks!
I usually don't do much rendering of js in applications so I'm a bit rusty on the specifics. However there are a couple of problems with your code.
First by issuing a redirect your instructing the browser to load a new url . Any variables such as 'conversation' that you would have set would be forgotten.
As the Stan Wiechers alluded you need to use an instance variable (e.g. #conversation) if you want to preserve conversation for the view. Unfortunately that won't help you in this case because of the redirect which wipes out all variables not stored in the session, cookies, or flash hash.
What I think you want to do is render your partial in stead of redirecting. Typically when you are using ajax you don't want to reload the page on the server side. In Rails you would typically render json or in your case a js partial.
Try
format.js{render partial:[PARTIAL NAME], locals:{conversation: conversation} }
This will render the partial without redirecting and will pass your local variable. If you change 'conversation', to #conversation then you can leave off the locals:{conversation: conversation} but your partial should reference
#conversation
not
conversation
hope that helps

Is it possible to use redirect_to when it's called by remote ajax?

Now this action in this controller is called by remote ajax call.
Only when the checkbox[:call] was checked and it's submit,
I'd like make it to redirect to ......_path with flash message.
Is it possible? if possible, how?
controller
.....
if params[:comment][:call] == "1"
flash[:notice] = "you checked and submit!"
redirect_to ....._path
else
ajax page reload
end
view Form (remote with ajax)
<%=form_for(([#community, #comment]), :remote => true, :class => 'form' ) do |f| %>
<%= f.check_box :call, :label => 'call' %> call
<div class="form-actions">
<div class="input-append">
<%= f.text_field :body, :id => "input", :class => "box" %>
<button type="submit" class="btn">submit</button>
</div>
</div>
<% end %>
Comment model
attr_accessible :icon, :call
....
def call
#call ||= "0"
end
def call=(value)
#call = value
end
You will have to write this code in js instead of controller.
In controller:
def action_name
....
respond_to do |format|
format.js
end
end
Make a action_name.js.erb file and write this code:
<% if params[:comment][:call] == "1" %>
<% flash[:notice] = "you checked and submit!" %>
window.location.href = <%= some_url %>
<% else %>
$("#some_div_id").html("something") //ajax page reload
<% end %>
Hope this will work for you.
No, it is not possible.
You have to render javascript that will change the window location:
window.location.href = 'http://your new location';
Of course, in your js view, you are able to use dynamic value for the url using:
window.location.href = '<%= #a_controller_variable %>';

Rails: Access parameters in view after form submission

In my Rails 3.2 project, I have a form to create a new site in new.html.erb in app/views/sites/
<%= form_for(#site) do |site_form| %>
...
<div class="field">
<%= site_form.label :hash_name %><br />
<%= site_form.text_field :hash_name %>
</div>
...
<div class="actions">
<%= site_form.submit %>
</div>
<% end %>
Then the create function in sites_controller.rb
def create
#site = Site.new(params[:site])
respond_to do |format|
if #site.save
format.html { redirect_to #site }
else
format.html { render action: "new" }
end
end
end
Then after the user submits, I want to show the hash_name that the user just submitted, in show.html.erb
You just put in <%= params[:hash_name] %>.
But accessing params[:hash_name] doesn't work. How can I access it?
You're redirecting to a different action - this will reset all the parameters you passed to the create action.
Either pass hash_name as a parameter like the other answer suggests, or just fetch it straight from the #site object.
Just append them to the options:
redirect_to #site, :hash_name => params[:hash_name]

Resources