multipleselect is forgeting selected values after proceed - javascript

Multiplyselect is forgetting owners values after searching.
After proceed i got params[:search] and params[:owners] but only input for search is filled-in. This is my code.
def index
#all_owners = Owner.select('distinct name').pluck(:name)
#animal = Animal.search(params[:search])
#animal = #animals.joins(:owners).where("owners.name IN (?) ", params[:owners].present? ? params[:owners] : #owners)
end
#------------------------------------------
<%= form_tag animals_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search]%>
<%= select_tag :owners, options_for_select(#all_owners),id: "multiselect-id", multiple: true %>
<%= submit_tag "Search", :name => nil %>
<% end %>
<% #aminals.each do |animal| %>
<%= animal.name %>
<%= animal.owners.map(&:name).join(', ') %>
<% end %>
<script type="text/javascript">
$(document).ready(function() {
$('#multiselect-id').select2();
});
</script>

You forgot to specify the currently selected values in the select_tag. This is done e.g. by a second argument to the options_for_select helper, i.e. something like: options_for_select(#all_owners, params[:owners] || #owners).
See the docs here.

Related

Rails will_paginate endless scroll with an array that drops the first 3 items

I have a partial where I'd like to drop or not show the first three articles in the array because they are in a featured articles section. I also want the partial to use will_paginate w/ endless scrolling to load the next page of articles. The issue I'm facing is that when using #articles.drop(3).each do |a| and the next page goes to load, the array drops the next three articles again.
What's the best way to solve for this? My initial thought was an array within an array, where the first array drops the first 3 then the nested array returns all articles but I'm not sure how to do that?
Array code in partial:
<% #articles.drop(3).each do |a| %>
<%= link_to a.source_url, :class => "flexRow" do %>
<%= a.source %>
<h3><%= a.title %></h3>
<% end %>
<% end %>
Index.js.erb
$('#article-index').append(' <%= j render("articles") %>');
<% if #articles .next_page %>
$('.pagination').replaceWith('<%= j will_paginate(#articles, :previous_label => '', :next_label => '', :page_links => false) %>');
<% else %>
$('.pagination').remove();
<% end %>
Index.html.erb
<div id="article-index">
<%= render 'articles' %>
</div>
UPDATE
This solution seems to work but doesn't feel elegant?
<% (#articles.current_page == 1 ? #articles.drop(3) : #articles).each do |a| %>
Try
#articles[3..#articles.count]
This will drop the records held at index 0, 1 and 2, and return the remaining.
You may do the following in your controller:
EXAMPLE
#articles = Article.where(...).paginate(page: params[:page], per_page: 10)
# Works only for the first HTML request
unless request.xhr?
#articles.shift(3)
end
.
.
.
respond_to do |format|
format.html
format.js
end
Now, when you iterate over #articles, it would start from index 3, only for first time.
EDIT
<% (request.xhr? ? #articles : #articles[3..10]).each do |a| %>
<%= link_to a.source_url, :class => "flexRow" do %>
<%= a.source %>
<h3><%= a.title %></h3>
<% end %>
<% end %>
Assuming the page size is 10.

select user and then dropdown of his challenges

A user has_many challenges.
When a user is selected...
<%= f.select :user_id, options_for_select(#challengers.collect { |challenger| [challenger.full_name] }) %>
... how can we show another dropdown with a list of his challenges?
<%= f.select :challenge_id, options_for_select(#challenger_challenges.collect { |challenged| [challenged.full_challenge]}) %>
In other words, how can we make "#challenger_challenges = the selected user's challenges"?
As it stand I get an error undefined method 'collect' for nil:NilClass since #challenger_challenges is nil.
OPTION 1
In challenges_controller I could do this:
#challengers = User.all
#challenger = User.find(params[:challenger_selected]) if (params[:challenger_selected]).present?
#challenger_challenges = #challenger.challenges
And then I would just need a way to refresh the page once a user is selected so that the user ID is passed in the params as :challenger_selected
OPTION 2
Achieve the aim of this question without the need of a page refresh. *Preferable
UPDATE
Based upon the comments below I realize I need to elaborate.
A user has_many challenges.
A user can create a duel.
In a duel there are two duelers.
The creator of the duel selects his own :challenge_id and then he selects the other dueler as well as one of his :challenge_id and then sets the #duel.consequence the dueler will have to do if he fails his challenge. The other dueler will get a duel request notification and then has the choice to accept or decline the conditions of the duel.
challenges.show.html.erb
<%= render 'duels/form' %>
duels/_form.html.erb
<%= simple_form_for(#duel) do |f| %>
<%= f.fields_for :duelers do |dueler| %>
<%= f.hidden_field :challenge_id, :value => #challenge.id %>
<%= #challenge.full_challenge %>
<% end %>
<%= f.fields_for :duelers do |dueler| %>
<%= render 'duels/dueler_fields', :f => dueler %>
<% end %>
<%= button_tag(type: 'submit', class: "btn", id: "challenge-create-save") do %>
Request Duel
<% end %>
<% end %>
duels/_dueler_fields.html.erb
<%= f.select :user_id, options_for_select(#challengers.collect { |challenger| [challenger.id] }) %>
# Trying to make this responsive to the user that is selected above
<%= render 'challenges/select', :f => f %>
<script>
$('#duel_duelers_attributes_1_user_id').change(function () {
var challenger_id = $(this).find(":selected").val();
var address = "<%= select_path %>".concat(challenger_id);
$.get(address, function(data) {
$("#duel_duelers_attributes_1_challenge_id").html(data);
});
});
</script>
routes
get 'challenges/select/:id' => 'challenges#select', as: 'select'
challenges/_select.html.erb
<%= f.select :challenge_id, options_for_select(#challenger_challenges.collect { |challenged| [challenged.full_challenge]}) %>
challenges_controller
def select
if (params[:challenger_id]).present?
#challenger = User.find(params[:challenger_id])
else
#challenger = User.find(1)
end
#challenger_challenges = #challenger.challenges
end
Credit for this should go to #Fallenhero - I am just explaining it in more detail.
You need to be able to identify the select tag.
<%= f.select ..., :html => {:id => :first} %>
You also need somewhere to put the second one.
<div id="second"></div>
Using jQuery:
$('#first').change(function () {
var challenger_id = $(this).find(":selected").val();
var address = "<%= [prints address to new select tag] %>".concat(challenger_id);
$.get(address, function(data) {
$("#second").html(data);
});
});
The address Ruby prints out should look something like challenges/select/ depending on how you want to design it. The / at the end is important.

jQuery ajax call from a numberfield using Rails is not working

For my application, I have fixeddeposits where we can create new fixeddeposits. Now, i want to update the rateofinterest field based upon the number(365/730/1095/1460 & 1825) I typed in the deposit period(number_field) and i have to check the customer age.
I have calculated customer age in fixeddeposits_controller. I don't know where i am wrong that too is not working.
Example 1:
1.1: If a customer age >58 && age<75, i want to open the fixed deposit for 365days means i have to sum the two fields rate(9.5%) + seniorincrement(0.5%) and then pass the value(10.0%) to rateofinterest field.
1.2: If a customer age >75, i want to open the fixed deposit for 365days means i have to sum the two fields rate(9.5%) + superseniorincrement(1.0%) and then pass the value(10.5%) to rateofinterest field.
1.3: If a customer age <58, i want to open the fixed deposit for 365days means i have to pass the rate(9.5%) field value alone to rateofinterest field.
Where as(rate, seniorincrement, superseniorincrement)fields are from interestrates table.
For this i am using AJAX/JQUERY which was suggest by Mandeep in my previous question.
I have implemented, but its not working. I have attached the code i tried. Kindly check it and please give me some ideas.
_form.html.erb
<%= form_for #fixeddeposit do |f| %>
<% if #fixeddeposit.errors.any? %>
<h4>Couldn't open FD Account</h4>
<ul>
<% #fixeddeposit.errors.full_messages.each do |error| %>
<li><%= error %></li>
<% end %>
</ul>
<% end %>
<%= f.label :customer_name, class:'required' %>
<%= f.text_field :customername, :placeholder =>'Name' %>
<%= f.label :date_of_birth, class:'required' %>
<%= f.date_select :dateofbirth, { :include_blank => true, :start_year => 1900, :end_year => 2014 }, :id => "dateofbirth" %>
<%= f.label :Periods, class:'required' %>
<%= f.number_field :periods, :id => "fixeddeposit_periods", :placeholder => "Days", :class => "input-mini" %>
<%= f.label :Rate_Of_Interest %>
<%= f.text_field :rateofinterest, :id => "fixeddeposit_rateofinterest", :value => "", :disabled => true, :class => "input-medium" %>
<span class="help-block">auto-generated</span>
<div>
</div>
<%= f.submit "Open FD", class: "btn btn-primary" %>
<% end %>
</div>
</div>
application.js
$(document).on("change","#fixeddeposit_periods",function(){
var periods = $(this).val();
var dateofbirth = $("#dateofbirth").val();
$.ajax({
type: "POST",
url: "/rateofinterest",
data: { periods: periods, dateofbirth: dateofbirth }
});
});
fixeddeposits_controller
def calculate_age(dateofbirth)
#age = DateTime.now - dateofbirth/ 365
end
def calculate_rateofinterest
#periods = params[:periods]
#dateofbirth = params[:dateofbirth]
calculate_age(#dateofbirth)
if #age >= 58 && #age < 75
#rateofinterest = Rateofinterest.select('interestrates.id, interestrates.seniorincrement')
elsif #age >= 75
#rateofinterest = Rateofinterest.select('interestrates.id, interestrates.superseniorincrement')
else
#rateofinterest = Rateofinterest.select('interestrates.id, interestrates.rate')
end
respond_to do |format|
format.html{ redirect_to fixeddeposits_path }
format.js{}
format.json{}
end
end
calculate_rateofinterest.js.erb
$("#fixeddeposit_rateofinterest").val(#rate);
routes.rb
resources :fixeddeposits do
resources :interestrates
end
post "/rateofinterest" => "fixeddeposits#calculate_rateofinterest" , as: "calculate_rateofinterest"
I don't know why it is not working. Help me to solve this issue.
First of all, in your js code replace
var dateofbirth = $("#fixeddeposit_dateofbirth").val();
with
// you have mentioned your dob field's id as 'dateofbirth'
var dateofbirth = $("#dateofbirth").val();
In your controller, you need to call calculate_age method to have #age variable. Replace
#dateofbirth = params[:dateofbirth]
with
#dateofbirth = params[:dateofbirth]
calculate_age(#dateofbirth)
I'm not sure, why you have written #age.save in your calculate_age method definition. You may remove it.
Now in your calculate_rateofinterest.js.erb file replace
$("#interestrates_rate").val(#rate);
with
$("#fixeddeposit_rateofinterest").val(#rate);
Hope it will help you.

Live Search with AJAX Ruby on Rails

I'm following the railscasts rails ajax tutorial and geting into some trouble. Everything went well, except the live keyup. The live search does not work, I have to click the search button to get the result.
Here is my application.js
$("#emos_search input").keyup(function() {
$.get($("#emos_search").attr("action"), $("#emos_search").serialize(), null, "script");
return false;
});
index.html.erb
<%= form_tag emoticons_path, :method => 'get', :id => "emos_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<div id="emos"><%= render 'emos' %></div>
<% end %>
emoticons_controller.rb
def index
#emoticons = Emoticon.search params[:search]
end
emoticon.rb
def self.search(search)
if search
where('name LIKE ? or emo LIKE ?', "%#{search}%", "%#{search}%")
else
scoped
end
end
I don't know what is the problem. I think I already followed the steps in tutorial. And there is nothing showed in js console.

Rails 3 javascript: How to render a partial with parameters

I'm still getting the hang of Rails. Here I'm using Rails 3 and the goal basically is to have an AJAX call triggered when I click the subscribe button the post_form partial is rendered beneath for the topic I have just subscribed to. The button then becomes an unsubscibe button and the post_form partial is removed. The toggling of the button alone works (i.e: by removing the second line in the two immediately following snippets), but the rendering of the *post_form* partial does not.
The problem is I can't seem to get the right syntax and/or passing of parameters in the two following partials. The topic object is just not passed and I get an invalid model_name for NilClass error when clicking on the subscribe or unsubscribe button. If I refresh the page manually, the partial is rendered or hidden the correct way, so it's really just the AJAX part that isn't working right.
views/subscription/create.js.erb
$("#subscription_form").html("<%= escape_javascript(render('users/unsubscribe')) %>");
$("#post_form").html("<%= escape_javascript(render('shared/post_form', :topic => #topic)) %>");
views/subscription/destroy.js.erb
$("#subscription_form").html("<%= escape_javascript(render('users/subscribe')) %>");
$("#post_form").html("<%= escape_javascript(render('shared/post_form', :topic => #topic)) %>");
views/users/_subscription_form.html.erb
<% unless current_user?(#user) %>
<div id="subscription_form">
<% if current_user.subscribed?(#topic) %>
<%= render 'users/unsubscribe', :topic => #topic %>
<% else %>
<%= render 'users/subscribe', :topic => #topic %>
<% end %>
</div>
<% end %>
controllers/subscriptions_controller.rb
class SubscriptionsController < ApplicationController
before_filter :signed_in_user
respond_to :html, :js
def create
#topic = Topic.find(params[:subscription][:topic_id])
current_user.subscribe!(#topic)
respond_with #topic
end
def destroy
#topic = Subscription.find(params[:id]).topic
current_user.unsubscribe!(#topic)
respond_with #topic
end
end
views/shared/_post_form.html.erb
<%= form_for(#post) do |f| %>
<div class="field">
<%= f.hidden_field :topic_id, :value => #topic.id %>
<%= f.text_area :content, placeholder: "Tell us about it ..." %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
If it is of any help, the relationships are:
post -> belongs_to -> topic and topic -> has_many -> posts
Looks like you're using the variable "#post" in the "views/_post_form.html.erb" file.
<%= form_for(#post) do |f| %>
Since you aren't setting that variable anywhere in your actions you would get a null reference error.
You would need to do something like this:
def create
#post = Post.find(the_post_id)
#topic = Topic.find(params[:subscription][:topic_id])
current_user.subscribe!(#topic)
respond_with #topic
end
Also you are passing in the "topic" variable as a local but accessing it as an instance variable. You should change the your _post_form.html.erb file to look like this:
<%= form_for(#post) do |f| %>
<div class="field">
<%= f.hidden_field :topic_id, :value => topic.id %>
<%= f.text_area :content, placeholder: "Tell us about it ..." %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
I don't have my ruby environment readily available so I can't verify that this will solve your problem but I think it should move you in the right direction.

Categories