Use javascript variables in Rails view helpers - ruby-on-rails

Using jqGrid I want to generate delete links for each row in the grid. The standard way to do this is to add the links in the gridComplete callback like shown below:
gridComplete: function() {
var ids = jQuery("#jobs_table").jqGrid('getDataIDs');
for(var i=0;i < ids.length;i++){
var cl = ids[i];
be = '<%= link_to(image_tag("delete.gif", :border=>0, :size=>"20x22", :alt => "delete"),⋅
{ :action => 'destroy', :id => 'cl', :method => :delete}, :class => 'ajax') -%>';
jQuery("#jobs_table").jqGrid('setRowData',ids[i],{workflow_state:be});
}
},
Using getDataIDs I get a list of IDs that I can use to generate the delete links. The problem is that this is a javascript call that results in a javascript variable.
The question is how can I use this variable "cl" inside rails link_to view helper?

Are you just wanting to add a delete button to each row?
If so why dont you just return a column called delete then add custom formatter in your javascript that returns the button.
Custom Formater

Related

url_for and remote: true

I've got an issue with Rails. I want a select form which render a partial view when clicked. I want the partial views to be effective without refreshing the whole document (Ajax) but it seems that remote: true does not work for me...
What I have currently and refresh the whole document:
= form_tag url_for(action: :index), method: 'get' do
//Storing some informations in html fields for further use
- shops_array = #shops.collect.with_index { |shop, i| [shop.title, shop.id, {'address' => [shop.address, shop.zipcode, shop.city].join(" ")}, {'id' => 'shop'+String(i)}] }
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", data: {submit_on_change: true}
What I've tried :
= form_tag url_for(action: :index), remote: true, method: 'get' do
//Storing some informations in html fields for further use
- shops_array = #shops.collect.with_index { |shop, i| [shop.title, shop.id, {'address' => [shop.address, shop.zipcode, shop.city].join(" ")}, {'id' => 'shop'+String(i)}] }
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", data: {submit_on_change: true}
How do I apply the remote: true option with url_for? If not possible, I could use some help finding a workaround.
As per the docs you can specify the remote option to the form_tag method, like so:
form_tag(url_for(controller: :charmander, action: :ember), remote: true, method: :get, class: 'pokemon-form') do
# form logic
end
However, this will only trigger the ajax:success event when the whole form is submitted.
From your question it seems to me that you want to re-render some partial when your select value changes. I'm not sure how you use the submit_on_change data attribute, but if I'm correct in assuming that you make it submit the entire form when the select vaule changes then all you need to do is listen for the ajax:success event for the entire form, like so:
$('.pokemon-form').on('ajax:success', function (event, data, status, xhr) {
// Do something with data, which would be the rendered partial returned
// from the server call.
});
Ended up using an onclick and a JavaScript function. Though it may not be the best solution nor the prettier, it works like a charm for me.
= select_tag :shop_id, options_for_select(shops_array, #shop_id), prompt: "Your shop :", onclick: 'ajaxSelectedShop('+String(8)+')'

rails - link_to same page but with anchor -> no reload

I want to use
link_to 'Cancel', edit_project_path(#project, url_options)
to cancel the edit and go back to the edit page.
I use jQuery UI Tabs for a tabbed edit page. Each tab has it's own form and submit/cancel buttons.
When I click a Cancel link I want to go back to the active tab. So I set
url_options = {:anchor => active_tab_id}
The problem is: the page doesn't reload because of the anchor.
Adding data-no-turbolink does not help:
link_to 'Cancel', edit_project_path(#project, url_options), :data => {:no_turbolink => true}
try using
<%=link_to("Cancel", edit_project_path(#project, url_options), method: :get)%>
this helped me better
The only way to do it is with javascript.
Add custom data attribute to the link:
link_to 'Cancel', edit_project_path(#project, url_options), :data => { :reload => true }
Then put this javascript somewhere, for example in app/javascripts/reload_hash.js
$(function(){
$('a[data-reload="true"').on('click', function(e) {
window.location = $(e.target).attr('href');
window.location.reload(true);
});
});

Creating associated records inside parent's new view/form. Associated records are done through Ajax/jquery-file-upload

So i have a "Style" model, which has_many "Images". In the new style page, i want to be able to add images all in the same page. However, since we did not create the style record yet, it does not have an ID. So how would i go about collecting all the images that are built/uploaded by ajax, and updating their style_id attributes after saving the new Style?
I am using jquery-file-upload to add images to the Image table, and upload my files to Rackspace cloud files. All of this is working, i just am not able to set style_id other than just manually setting it.
Is there a best practices/proper way to go about this, since jquery-file-upload uses Ajax, i am not sure the best approach to saving my parent. I am thinking the best approach would be to use ajax to submit the parent form as well, rather than use the dom, like adding hidden inputs/elements to the parent form?
thank you
Style: form partial
<%= form_for #style, :html => {:multipart => true} do |f| %>
//NORMAL RAILS FORM CODE HERE
<% end %>
<%= form_for Image.new, :html => { :multipart => true, :id => "fileupload" } do |f| %>
<%= f.file_field :file, :multiple => true %>
<% end %>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '<%= style_images_path(1) %>',
add: function (e, data) {
data.context = $('<div class="img uploading"/>').text('Uploading...').appendTo(document.body);
data.submit();
},
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<img src="'+file.thumbnail_url+'">').appendTo(data.context);
});
console.log(data);
data.context.append("<span>done</span>");
},
option: {
autoUpload: true,
}
});
});
</script>
In the above code you can see I set the style_id manually... style_images_path(1)
-
MY PROPOSED SOLUTION:
My idea is to pass an array of the id's of all children (images) to the create/update method of style. and in the controller, update all the style_id attributes of the matching id's to the newly created style's id... I think this is possible?
That's tricky.
You can instantiate the #style from within the new method of your controller.
Instead than:
#style = Style.new
put
#style = Style.create
If validation complains, than use the following workaround:
#style = Style.new
#style.save :validate => false
Now in your view you have a fully qualified #style with an ID you can pass over to js:
url: '<%= style_images_path(#style) %>',
At this point when (if ever) the user clicks on the form button, the control reaches the update method, not the create (this is because the _form.html.erb automatically changes the HTTP verb from POST (create) to PUT (update). So make sure your controller is ready for this).
You should also consider some sort of "garbage collection" in case Style objects get created and never saved. This might not be straight forward because the user can always close the window and you are left with an incomplete Style in the db. Maybe some js function that triggers at window close and calls a garbage_collect_if_not_saved(#style) method? Still not perfect (what if the browser hangs?) but better than nothig. Otherwise a good-old cron based script that cleans the db up.
Cheers,

How do I build link with specific part of params hash from previous request?

While I wouldn't normally create a page like this, please know this is a current constraint I can't change.
The page has a checkbox form as well as a table with links for THs that sort the table. I need to construct the TH link in a way that it retains the checkbox items already checked.
Checkbox constructed in View with Haml as:
= form_tag movies_path, :method => :get do
Include:
- #all_ratings.each do |rating|
= rating
= check_box_tag "ratings[#{rating}]", "1", (#ratingsarray.include?(rating) ? true : false)
= hidden_field_tag 'sort', #sort
= submit_tag 'Refresh'
Then for the table it has this for the TH
%th{:class => #classrelease_date}
%a#release_date_header= link_to "Release Date", movies_path(:sort=>'release_date', :params[:ratings]=>params[:ratings])
Ultimately I want the URL like "/moves/?sort=release_date&Ratings[PG]=1&Ratings[G]=1" where I am spitting out the ratings params back to the page as part of the URL. Or how to I pass the ratings params in any part of page where the existing controller code will read it.
Existing controller code access ratings from checkbox:
params[:ratings]
Since movies_path accepts hash as parameter, you can tailor params and then generate the URL with movies_path(params). Generally, you may need to remove "controller" and "action" from params.

passing large arrays via link_to function (or by other means) in Rails

I know that link_to uses get action by default and also you can change the method to post by passing :method => :post to link_to function, but it does not seem to work. Here is the syntax that I am using:
= link_to "Export" export_path(:data_array => d_array), :method => 'post'
But this does not seem to work. The array is being passed by as a query parameter which I can see in the URL box and it bombs my application since it blows the string length limit in the url string.
Try using form instead:
= form_tag export_path do
- d_array.each do |val|
= hidden_field_tag 'data_array[]', val
= submit_tag 'Export'
Notice that in a controller params[:data_array] will be an array of strings.

Resources