How to save ids in the cookies - ruby-on-rails

I am using will_paginate to list a huge ammont of files in different pages. I also have a check_box in order to choose files for the futher analysis.
controller:
#files = FileDB.search(search_string).paginate(:per_page => 10, :page => params[:page])
view:
<button type="button" id="check_all">Check/Uncheck all</button>
<%= button_tag :class => "btn btn-primary", :name => 'analyse' do %>Analyse<% end %>
<% #filess.each do |file| %>
<p><td> <%= check_box_tag "files[]", file.id %></td><%= file.name %></p>
lala...
My problem is that I can choose the files which are situated in one page.So by clicking on "check/uncheck all" it checks not all available files, but files of this specific page. I would like to be able to check different files from different pages together.
Example: 10 files on the page 1, 4 files on the page 2. I want to check 5 files from page one and all files from page 2 and then by clicking on the buttom "Analyse", those 9 files have to be analyzed together, so the checkbox should remember different files from different pages
I know it is possible to save ids in the cookies, but I have found nothing in internet how to do it. I need just a small example
Thanks in advance
edit:
or maybe there is an alternative to the will_paginate that uses POST?
edit2: according to Muntasim
<script type='text/javascript'>
$('#check_all').on("click", function(){ $('input[type="checkbox"]').click(); });
</script>
<script src="/assets/rails.validations.js" type="text/javascript"></script>
<script src="/assets/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
var checkedIds = $.cookie('checked_file_ids');
$('p td input[type=checkbox]').on('change', function () {
if($(this).is(':checked')) {
checkedIds.push($(this).val())
}
else {
checkedIds.splice(checkedIds.indexOf($(this).val()), 1);
}
$.cookie('checked_file_ids', checkedIds);
})
</script>
<%= form_for Group.new, url: what_to_do_files_path ,method: :get ,:validate => true do |f| %>
<div class="field">
<%=f.text_field :group_name, placeholder: "Group Name" %>
</div>
<%= button_tag :class => "btn btn-primary", :name => 'analyse' do %>Analyse<% end %>
<button type="button" id="check_all" class="btn"> Check/Uncheck All</button>
<% #files.each do |file| %>
<p><td> <%= check_box_tag "files[]", file.id , false %></td><%= file.name %></p>
<%end%>
<%end%>
And in a controller:
def what_to_do
ids_to_compare = cookies['checked_file_ids']
end
But ids_to_compare is empty

You can simply do:
cookies[:ids] = #All checked ids
And then to retrieve the ids you can easily call the cookie like this:
cookies[:ids]

if you want to use cookie:
use jquery.cookie
Now put this in the view
<script type="text/javascript">
var checkedIds = $.cookie('checked_file_ids');
$('p td input[type=checkbox]').on('change', function () {
if($(this).is(':checked')) {
checkedIds.push($(this).val())
}
else {
checkedIds.splice(checkedIds.indexOf($(this).val()), 1);
}
$.cookie('checked_file_ids', checkedIds);
})
</script>
now when you need to compare them you can get the ids: (likely in a controller)
ids_to_compare = cookies['checked_file_ids']

Related

Render partial through js.erb

Im trying to render a form to add a comment via jquery, but i keep getting this error:
undefined method `render' for #<#<Class:0x007fc8aaa18860>:0x007fc8a0fddfc0>
Here is the js.erb file:
$(document).on('turbolinks:load', function(){
console.log('test');
$('.reply-comment-form').on('click', function(e) {
e.preventDefault();
body = this.id;
$('.nest-' + body).append( "<%= escape_javascript(render partial: 'comment_reply_form')%>");
});
});
Ive tried multiple different iterations of the code but still the same error.
When i try say, this for example:
$('.nest-' + body).append( " This is a test");
It does as it should do.
Ive checked the other questions here and i cant see anything different to what i'm doing so i'm a little stuck.
Here is what im trying to render:
<div class="body">
<span class="tip tip-left"></span>
<div class="message font-medium">
<%= form_for #message do |form| %>
<%= form.label :Reply_to_comment %> <br />
<%= form.text_area :content, :rows => 5, :cols => 80, autofocus: true %> <br />
<%= form.hidden_field :entry_id, value: params[:entry_id] %>
<%= form.hidden_field :parent_id, :value => params[:parent_id] %>
<%= form.submit "Submit"%>
<% end %>
</div>
<div class="flerowspb">
<span class="font-small">
</span>
</span>
</div>
</div>
Thanks
Ok so I've come across the answer, I cant call render from the assets folder.
Here is the link
Try to the following
$('.nest-' + body).append( "<%= escape_javascript(render("messages/comment_reply_form"))%>");
or
$('.nest-' + body).html("<%= escape_javascript(render("messages/comment_reply_form")) %>");
Try using j render:
$('.nest-' + body).append( "<%= j render 'comment_reply_form' %>");
and i think that path for partial view should be more accurate, like 'controller_name/view/partial' , or whatever you have in your code.

Defaults not set in Rails multiple-select form

In my application, one article can have multiple tags. When creating an article, I am able to add multiple tags to an article using a multiple-select dropdown and the Rails Select2 gem.
The problem is that when I edit the article, none of the tags are selected, and a user has to select them all over again.
<%= form_for(#article) do |f| %>
<%= f.select :tags, options_for_select(#tags.collect {|t| [ t.id, t.title] }),{:selected=>#article.tags}, :multiple => true, :id => "article_tags", :class => "form-control" %><br>
<%= f.submit 'Update', :class => "btn" %><br>
<% end %>
<script>
$(document).ready(function() {
$("#article_tags").select2({multiple:true});
});
</script>
Any suggestions?
This ended up working when I put it at the bottom of the page:
<script>
$(document).ready(function() {
$("#tags").select2({multiple:true});
$('select').select2().select2('val', 'tag one, tag two, tag three');
$('select').select2();
});
</script>

Rails 4 & Coffee Script form helper to hide on unchecked field

I am trying to make an app in Rails 4.
I use simple form for the form and have a js form helper file which I use to have javascript hide or show form elements depending on how users answer questions as they move through the form.
My problem is that this js function works fine on the initial create, but if i come back to edit the form, the reminder id content is shown when the draft attribute is == false.
Is there another way to approach this problem?
My form has:
<%= f.simple_fields_for :scope do |finalises_s| %>
<%= finalises_s.simple_fields_for :finalise do |dr| %>
<div class="row">
<div class="col-md-3 col-md-offset-1">
<%= dr.label :draft, 'Would you like to save this draft and finish it later?', class: 'question-project' %>
</div>
<div class="col-md-7">
<%= dr.collection_radio_buttons :draft, [[true, ' Yes, save a draft'], [false, ' No, publish it']], :first, :last, {:item_wrapper_class => 'fixradio'}, {:class => "response-project"} %>
</div>
</div>
<div id="reminder">
<div class="row">
<div class="col-md-3 col-md-offset-1">
<%= dr.label :reminder, 'Would you like a reminder to complete this draft?', class: 'question-project' %>
</div>
<div class="col-md-7">
<%= dr.collection_radio_buttons :reminder, [[true, ' Yes'], [false, ' No']], :first, :last, {:item_wrapper_class => 'fixradio'}, {:class => "response-project"} %>
</div>
</div>
My js form-helper file has:
if $("input:radio[name='"+ inString + "[scope_attributes][finalise_attributes][draft]']").is(':checked')
$('#reminder').show()
else
$('#reminder').hide()
$(document).on 'change', "input:radio[name='"+ inString + "[scope_attributes][finalise_attributes][draft]']", ()->
if $(this).val() == 'true'
$('#reminder').show()
else
$('#reminder').hide()
There are probably a few different ways to do this, but I did something very similar.
Attach an id or class to the radio button you can use to bind later (in my case, for each radio/value combination, I added a unique class like class: this_radio_value_true).
Similarly, attach an id or class to the sections of markup you want to impact (in my case, I added an id to a form_group which I wanted to hide/show like id: stuff_to_control).
Trigger jQuery for these elements:
$('.this_radio_value_true').on('click', function() {
$('#stuff_to_control').show();
});
$('.this_radio_value_false').on('click', function() {
$('#stuff_to_control').hide();
});
It's probably because TurboLinks. You can't use $(document).on 'change'. You have to listing for TurboLink events. Rails doesn't load the entire page each time. It only loads the content inside the layout. You have to use
$(document).on 'ready page:load', ->
Here's the docs: https://github.com/rails/turbolinks/#events
Guide: http://guides.rubyonrails.org/working_with_javascript_in_rails.html#page-change-events

Rails search URI with unwanted parameters?

Background
I am creating a search field in my header. This code in my view:
<% if signed_in? %>
<%=f orm_tag( "/search", method: "get", :class=>"navbar-form navbar-left", :role => "search") do %>
<div class="form-group">
<%=t ext_field_tag :q, nil, :class=>"form-control", :placeholder => 'Domain/IP Search' %>
</div>
<%=b utton_tag "Search", :type=>'submit', :class=> "btn btn-primary" do %>
<span class="glyphicon glyphicon-search"></span>
<% end %>
<% end %>
creates this output:
<form accept-charset="UTF-8" action="/search" class="navbar-form navbar-left" method="get" role="search">
<div style="display:none">
<input name="utf8" type="hidden" value="✓">
</div>
<div class="form-group">
<input class="form-control" id="q" name="q" placeholder="Domain/IP Search" type="text">
</div>
<button class="btn btn-primary" name="button" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</form>
Here is a picture:
The issue
The problem is when I search, I get this in my url:
/search?utf8=✓&q=test&button=
Ideally, I'd like it to be more like:
/search?q=test
tl;dr:
How do I get rid of the button parameter (and hopefully the utf one as well).
Extra info:
routes.rb
resources :search
search_controller.rb
class SearchController < ApplicationController
def index
#results = params[:q]
puts #results.to_s
end
end
search\index.html.erb
<%=#results.to_s %>
EDIT, answer
Adding this because while the accepted answer helped me get to the solution; it didn't have the exact code for my circumstance. I made these changes:
1) routes:
match '/search', to: 'search#index', via: 'post'
2) form in my header:
<%= form_tag search_path, method: "post", :class => "navbar-form navbar-left", :id=> "SearchForm", :role => "search" do %>
<div class="form-group">
<%= text_field_tag :q, nil, :class => "form-control", :placeholder => 'Domain/IP Search' %>
</div>
<%= button_tag "Search", :type=> 'submit', :class=> "btn btn-primary" do %>
<span class="glyphicon glyphicon-search"></span>
<% end %>
<% end %>
GET
The bottom line, as I wrote in another answer, is that you're using GET:
Essentially, when you submit a GET form, it appends the parameters to your URL, whilst a POST form will append the data to the request body (or somewhere hidden).
The difference is just that the GET request expects a response to be returned immediately, and so you have to pass the parameters in the URL to ensure the server knows how to construct it. The best example being if you use a GET request to load a page.
The POST method is used primarily used for forms, where a response is not expected immediately; thus allowing you to keep the params hidden in the request.
Fix
We've actually created a basic search feature here (the actual search doesn't work for some reason, but the live search does)
The way we did it was as follows:
match 'search(/:search)', :to => 'products#search', :as => :search, via: [:get, :post]
This will firstly allow you to access the search action by typing domain.com/search/your-query-here
In terms of submitting via a form, you'll be able to use JQuery to amend the URL with the input from the text field:
#app/views/elements/_nav.html.erb
<%= form_tag search_path, :method => :post, :id => "SearchForm" do %>
<%= text_field_tag :search, params[:search], placeholder: 'Search your favourite products or brands', :autocomplete => :off, :id => 'SearchSearch' %>
<%= image_submit_tag('nav_bar/search.png', title: 'Search', class: 'search_submit', data: { "placement" => "bottom" }) %>
<% end %>
#app/assets/javascripts/application.js
//Search Submit
$(document).ready(function() {
$('#SearchForm').submit(function(e) {
e.preventDefault();
if( $('#SearchSearch').val().length > 0 ) {
var search_params = '/' + $('#SearchSearch').val().toLowerCase();
}else{
var search_params = ''
}
window.location.href = $(this).attr('action') + search_params
});
});
If you are not doing with the Utf8 parameter but, Rails is & but its needed. It's to correct some issues in IE's parameter encoding, This parameter was added to forms in order to force Internet Explorer 5, 6, 7 and 8 to encode its parameters as unicode.Its fixes encodeing issue of IE.
Please refer following link:
What is the _snowman param in Ruby on Rails 3 forms for?
This parameter is a feature of rails.
It was previously the snowman.
It helps IE to really use utf-8.
Avoid using form_tag and it works:
<form action="<%= search_path %>" method="get" >
<%= text_field_tag 'query' %>
<%= submit_tag "Search", :name => nil%>
</form>
Now style your form as you want

Bootstrap Twitter Popup works only for the first record in rails

I have the following view in my Ruby on Rails application. I want to be able to display a content of a .txt File (the path is saved in <%=file.info%>) with a popup. I included already a form for a popup. The problem is in the javascript. If I place the following javascirpt before form_tag
EDIT
<script type='text/javascript'>
$(function(){
$("#blob").popover({ title: 'info' });
});
</script>
it works only for the first record, another Info-buttons do not popup. And theoretically, i have to put the javascript after <div class="my_view"> but then it does not work at all.
<%= form_tag what_to_do_files_path, method: :get do %>
<%= button_tag :class => "btn btn-primary", :name => 'pictures' do %> Analyze<% end %>
<button type="button" id="check_all" class="btn"> Check/Uncheck all</button>
<%= button_tag :class => "btn btn-warning", :name => 'delete' do %>Delete <% end %>
<% #files.each do |file| %>
<div class="my_view">
<p><td></td><%= check_box_tag "fils[]", file.id %> <%= file.name %></p>
<% laa=File.read("#{Rails.root}"+"/public"+file[info]) %>
hover for popover
SO, my question is: How can I display the .txt File for each record, saved in the database ?
Thanks in advance
Don't use an ID to tag your "blob", use a class. You are only allowed to have one instance of an ID per page.
When calling $("#blob").popover({ title: 'info' });, it's going to go for the first instance of id="blob" that it finds. If you change it to a class, you can write
$(".blob").popover({ title: 'info' });
and it should work for all items which have the class blob.

Resources