render some partial after destroy method. Rails, haml - ruby-on-rails

I have a problem with destroy method. My idea is re-render partial, but partial should to do the check if #driving_informations.present?. So when I click link "delete" page do nothing, and data is staying in the page, when I press F5 and page reload everything ok - data not exist!
This is my controller method
def destroy
#driving_information.destroy
#user = #driving_information.user
#driving_informations = #user.driving_informations
render '_list.html.haml', layout: false
end
and View
%h4= t("driving_information.driving_info")
-if #driving_informations.present?
=render ("list")
-if #user == current_user
- #driving_informations.each do |driving_information|
= link_to t('common.edit'), edit_driving_information_path(driving_information), remote: true, data: { toggle: "modal", target: "#ajax-modal" }
= link_to t('common.delete'), driving_information_path(driving_information), method: :delete, remote: true, data: { confirm: t('common.confirm') }
-else
= link_to t('common.add'), new_driving_information_path, remote: true, data: { toggle: "modal", target: "#ajax-modal" } if #user == current_user
%p= t('driving_information.not_exists') if #user != current_user
:javascript
$(function(){
$("table.driving-information .destroy-btn").on("ajax:success", function(event, data, status, xhr){
$('#driving-information-block').html(data);
Any ideas?

I'd suggest that in your AJAX for on success of the destroy, target the form using jQuery and clear it. Assuming your form ID is form:
#('#form').find("input[type=text], textarea").val("");
Source: Clear form fields with jQuery

Related

Rails how to update the page with the help of Ajax

The object Task contains a boolean field done. How to Ajax refresh the page after the change of status? And instead true - false display value complete - incomplete?
routes.rb:
resources :tasks do
member do
post 'done'
end
end
Controller:
def done
#task = Task.find(params[:id])
#task.update_attributes(:done => params[:done])
respond_to do |format|
format.js {}
end
end
View:
....
<td><%= task.done %></td>
<td><%= check_box_tag 'done', task.id , task.done, :class => "task-check", remote: true %></td>
....
<script>
$(".task-check").bind('change', function(){
$.ajax({
url: '/tasks/'+this.value+'/done',
type: 'POST',
data: {"done": this.checked},
});
});
</script>
Update
edited script
<script>
$(".task-check").bind('change', function(){
$.ajax({
url: '/tasks/'+this.value+'/done',
type: 'POST',
data: {"done": this.checked},
}).done(function(ajax_response){
location.reload();
});
});
</script>
and controller
def done
#task = Task.find(params[:id]) # make sure you have this
#task.update_attributes(:done => params["done"])
render :json => { data: "Success", is_done: params[:done] }
end
How to update page content without having to reboot ?
Controller:
def done
#task = Task.find(params[:id]) # make sure you have this
#task.update_attributes(:done => params["done"])
render :json => { data: "Success", is_done: params[:done] }
end
View:
....
<td><%= task.done %></td>
<td><%= check_box_tag 'done', task.id , task.done, :class => "task-check" %></td>
....
<script>
$(".task-check").on('change', function(e){
// removed remote-true. you can preventDefault if you need to but doubt page tries to refresh from a checkbox getting checked. e.preventDefault() if you need it
$.ajax({
type: "POST",
url: '/tasks/done',
type: 'POST',
data: {done: $('.task-check').val()},
}).done(function(ajax_response){
// update whatever you want after it completes
});
});
</script>
Didn't test this but I write these all the time. Let me know if it doesn't work post the payload and I'll figure out what's missing.
If you just want to update the value from 'incomplete' to 'complete', you can simply target the element that's called incomplete. if it has a class of, say, 'task-status' you can target that element and update in the .done part of the function. For instance:
$('.task-status').text('Complete')
should replace what previously said incomplete. If it's a text input you might use .val() instead. If it's just text on the page .text() should work.

Checkbox in index view live updating

I'm currently learning rails and working on what I'm sure is everyone's first rails app, a simple todo list. I need to implement a checkbox next to the items to indicate whether they are complete or not. Each item has a boolean attribute called "completed" in their model. I have found a couple checkbox questions while searching but none explain the syntax very easily in the context of the index view.
Also, I really want the checkbox to work without a submit button. I know I could accomplish something like this using AngularJS's ng-model but I don't think it would be practical to implement angular for such a small thing and I don't know how angular works with rails.
If anyone could give me a pointer in the right direction, it would be greatly appreciated. Here's my index.html.erb for reference.
<h1>
To Do List
</h1>
<table>
<tr>
<% #todo_items.each do |item| %>
<!-- Checkbox here -->
<tc style="<%= 'text-decoration: line-through' if item.completed %>">
<%= link_to item.title, item %>
</tc>
<tc>
<%= item.description %>
</tc>
<tc>
<%= link_to "Edit", edit_todo_item_path(item) %>
</tc>
<tc>
<%= link_to "Delete",item, data:{:confirm => "Are you sure you want to delete this item?"}, :method => :delete %>
</tc>
<hr/>
<% end %>
</tr>
</table>
<p>
<%= link_to "Add Item", new_todo_item_path %>
</p>
This is my way, I don't know this way is right direction or not but this works for me (also different case but same of concept).
views for checkbox
You could put an id item or something into attribute of checkbox for find an object in controller if you send data to controller for get record of object, and you could define if attribute completed of record is true or false:
<%= check_box_tag :completed_item, 1, item.completed? ? true : false, { class: 'name-of-class', data: { id: item.id} } %>
controller
You need two action call set_completed and remove_completed, and also you don't need templates for them, just use format as json:
before_action :set_item, only [:set_completed, :remove_completed, :other_action]
def set_completed
#item.set_completed!
respond_to do |format|
format.json { render :json => { :success => true } }
end
end
def remove_completed
#item.remove_completed!
respond_to do |format|
format.json { render :json => { :success => true } }
end
end
private
def set_item
#item = Item.find params[:id]
end
Model
For set_completed! and remove_completed! you could define in your model
def set_default!
self.update_attributes(:completed => true)
end
def remove_default!
self.update_attributes(:completed => false)
end
routes
resources :address do
collection do
post 'set_completed'
post 'remove_completed'
end
end
Also, you need help JavaScript for handle send request from view to controller event click of checkbox:
jQuery
$(".completed_item").click(function(){
var check = $(this).is(":checked");
if (check == true){
set_completed($(this).attr('data-id'));
} else{
remove_completed($(this).attr('data-id'));
}
});
function set_completed(data_id) {
$.ajax({
type: 'POST',
url: "/items/set_completed",
data: { id: data_id},
dataType: 'json',
success: function(response){
if(response){
}else{
alert('error');
}
}
})
}
function remove_compelted(data_id) {
$.ajax({
type: 'POST',
url: "/items/set_completed",
data: { id: data_id},
dataType: 'json',
success: function(response){
if(response){
}else{
alert('error');
}
}
})
}

How to pass variable into controller action from view?

views/vehicles/_form.html.haml
= link_to "Deactivate", "/vehicles/deactivate"
I want to pass in #vehicle in my link_to above.
How do I do this?
controllers/vehicles_controller.rb
def deactivate
#vehicle = Vehicle.find(params[:id])
#vehicle.active = 0
#vehicle.save
respond_to do |format|
format.html { redirect_to vehicles_url }
format.json { head :no_content }
end
end
To make it easy and in Rails way, you can use Rails resources:
# routes.rb
resources :vehicles do
put 'deactivate', on: :member
end
# view:
= link_to 'Deactivate', deactivate_vehicle_path(#vehicle), method: :put
Best answer already given by Marek Lipka.
There is also a way using ajax
<%= link_to 'Deactivate', javascript::void(0), :class => "deactivate" %>
Put some script:
<script>
$(".deactivate").click(function() {
$.ajax({
type: "post",
url: "/vehicles/deactivate",
data: {id: <%= #vehicle.id %>},
dataType:'script',
beforeSend: function(){
// do whatever you want
},
success: function(response){
// do whatever you want
}
});
});
</script>
This worked for me, I ended up using the Update action in my controller.
= link_to "Deactivate", vehicle_path(#vehicle, :vehicle => {:active => 0}), method: :put, :class=>'btn btn-mini'

Implementing ajax request to create/edit rails object

I am trying to create a add/edit credit card form within my edit user page. To do so I am trying to implement an ajax call to the edit and create functions in my customers controller.
This is the code I have for the update button within the modal window:
<%= button_tag "Update", :class =>"btn submit-button", :type => 'button', :onclick => "onUpdateCard('#{current_user.id}');"%>
This is the function that it calls:
function onUpdateCard(id) {
this.id = id;
// disable the submit button to prevent repeated clicks
$('.submit-button').attr("disabled", "disabled");
var card_number = document.getElementById('card_number').value;
var card_code = document.getElementById('card_code').value;
var card_month = document.getElementById('card_month').value;
var card_year = document.getElementById('card_year').value;
var response = Stripe.createToken({
number: $('#card_number').val(),
cvc: $('#card_code').val(),
exp_month: $('#card_month').val(),
exp_year: $('#card_year').val()
}, stripeResponseHandler);
// allow the form to submit with the default action
return false;
};
function stripeResponseHandler(status, response) {
if (response.error) {
$(".payment-errors").text(response.error.message);
$(".submit-button").removeAttr("disabled");
} else {
var token = response['id'];
var new_url = "/users/" + this.id + "/customers/new";
var edit_url = "/users/" + this.id + "/customers/1/edit";
$.ajax({
type:'GET',
url: edit_url,
data: {'stripe_card_token': token}
});
}
return false;
};
And in the controller there is the edit function:
def edit
#user = current_user
#customer = #user.customer
stripe_customer = Stripe::Customer.retrieve(#customer.stripe_customer_token)
stripe_customer.card = params[:stripe_card_token]
stripe_customer.save
end
Can you help me figure out how to handle the ajax correctly? I'm not sure how to debug this properly...
Here I'm suggesting the alternative to handle update request using AJAX.
I'm not improving or correcting your code but giving you a way to handle AJAX requests in Rails 3.
a. view
Whatever information you wants to update in Database using AJAX call you will pass through a form. So for making a AJAX request you need to add :remote => true in your form. Rails provides this helper.
<%= form_for #customer, :url => admin_customers_path, :method => :post, :remote => true, :html => { :id => "customer-form" } do |form|-%>
<%= render :partial => 'admin/customers/form', :object => form %>
<%= form.submit 'Update' %>
<% end %>
In the _form.html.erb you can add textfield or other this whatever you wants to add in your edit form
b. controller
Because of " :remote => true " you form submission will make a JS request so in update action after saving the data of customer
control will for to format.js and then it will look for update.js.erb in views.
def update
if #customer.update_attributes(params[:customer])
respond_to do |format|
format.html {
flash[:success] = "customer's info was updated Successfully."
redirect_to customers_path
}
format.js
end
else
respond_to do |format|
format.html {
flash[:error] = #customer.errors.present? ? #customer.errors.full_messages.join('<br />') : "Oops! There is some problem with category update."
render :edit
}
format.js
end
end
end
c. update.js.erb
You can do stuffs after successful update. Suppose you want to highlight some div then you can do like this.
$('.target-div').effect("highlight", {}, 2500);

Rails checkbox AJAX call, don't want to render anything

I've got a little demo setup in which clicking a checkbox toggles an attribute via AJAX. It's working fine, but Rails REALLY wants to render something, so I've basically resorted to creating a blank toggle.js.erb file in my views.
Controller action in question:
def toggle
#task = Task.find(params[:id])
respond_to do |format|
format.js do
if (#task.status != true)
#task.status = true
else
#task.status = false
end
#task.save
render :layout => false
end
end
end
View in question:
<h1>Tasks</h1>
<ul style="list-style-type: none;">
<% #tasks.each do |task| %>
<li id="<%= dom_id(task) %>">
<%= check_box_tag(dom_id(task), value = nil, checked = task.status) %>
<%= task.action %> <%= link_to 'Edit', edit_task_path(task) %>
<%= link_to 'Delete', task, :confirm => 'Are you sure?', :method => :delete, :remote => true %>
</li>
<% end %>
</ul>
<%= link_to 'New Task', new_task_path %>
<script>
$$('input').each(function(el) {
el.observe('click', function(event) {
// Get the task ID
var elId = el.id.split("_")[1];
// Build the toggle action path
var togglePath = '/tasks/' + elId + '/toggle/';
// Create request, disable checkbox, send request,
// enable checkbox on completion
new Ajax.Request(togglePath, {
onCreate: function() {
el.disable();
},
onSuccess: function(response) {
},
onComplete: function() {
el.enable();
}
});
});
});
</script>
Without the blank toggle.js.erb file I've got in the views, Rails still gives me an error saying that it's trying to render something.
Ultimately, I'd like to both not have to have a blank toggle.js.erb file, and I'd like to get that Prototype stuff into my static JavaScript stuff and out of the view.
I'm pretty new to Rails, so there's probably an easier way to be doing this, but I'm kind of stuck here.
render :layout => false means that you want to render 'toggle' view without layout.
If you don't want render anything at all, you should use :nothing => true option
def toggle
#task = Task.find(params[:id])
#task.toggle! :status
# if it used only by AJAX call, you don't rly need for 'respond_to'
render :nothing => true
end
EDIT: In Rails4/5 you can use head :ok instead of render nothing: true, it's more preferable way to do this, but result is the same.

Resources