Using js.erb in rails - ruby-on-rails

In Rails 5 app with devise, I need to use a new.js.erb file to update select tag in my registrations view and controller. I cant seem to figure out why my new.js.erb file isn't working.
I've tried to use respond_to in controller as below,
registrations-controller.rb
def new
super
#cities = CS.get(:us,params[:state])
respond_to do |format|
format.js { render '/new.js.erb' }# layout: false }
format.html
end
end
new.html.erb
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), :remote => true) do |f| %>
<div class="signup-input-container">
<div class="field">
<%= f.text_field :firstname, autofocus: true, autocomplete: "firstname", placeholder: "First name", class: "signup-input-container--input" %>
</div>
<div class="field">
<%= f.select :state, options_for_select(CS.states(:us).map { |code, name| [name, code] }),{:prompt => "State"}, {:class => "signup-input-container--input", :id => "state-picker"} %>
</div>
<div class="field">
<%= f.select :city, options_for_select([]),{}, {:class => "signup-input-container--input", :id => "city-picker"} %>
</div>
</div>
<% end %>
new.js.erb
var city = document.getElementById("city-picker");
while (city.firstChild) city.removeChild(city.firstChild);
var placeholder = document.createElement("option");
placeholder.text = "Choose a city";
placeholder.value = "";
city.appendChild(placeholder);
<% #cities.each do |c| %>
city.options[city.options.length] = new Option('<%= c %>');
<% end %>
main.js
var state = document.getElementById("state-picker");
state.addEventListener("change", function() {
$.ajax({
url: "/states?state=" + state.value,
type: "GET"
})
})
I'm expecting this to create select tag options with my array of cities in my controller. Does anyone know how to get this to work?

To solve this you should just setup a separate controller where you can fetch the data from asynchronously and alternatively there are also several free API's which can be used for geographical lookup such as Googles Geocoding API and Geonames.
To setup a separate controller you can do it by:
# /config/routes.rb
get '/states/:state_id/cities', to: 'cities#index'
# /app/controllers/cities_controller.rb
class CitiesController < ApplicationController
# GET
def index
#cities = CS.get(:us, params[:state_id])
respond_to do |f|
f.json { render json: #cities }
end
end
end
I would skip using a .js.erb template altogether and just return JSON data which you can use directly in your JS or with one of the many existing autocomplete solutions. .js.erb only makes sense for extensive HTML templating (like for example rendering an entire form) where you want to reuse your server side templates - it greatly increases the complexity and generally makes a mess of your javascript which is not worth it just to output a list of option tags.
// If you are using jQuery you might as well setup a delegated
// handler that works with turbolinks,
$(document).on('change', '#state-picker', function(){
$.getJSON("/states/" + $(this).value() + "/cities", function(data){
// using a fragment avoids updating the DOM for every iteration.
var $frag = $('<select>');
$.each(data, function(city){
$frag.append$('<option>' + data + '</option>');
});
$('#city-picker').empty()
.append($('frag').children('option'));
});
});

Related

using the city-state gem in rails

Hey guys im currently working on a devise sign up form, the end goal is a user can select a state from the united states and a select tag below will populate with the correct cities in that state. im using the city-state gem. https://github.com/loureirorg/city-state
ive looked at other examples like this one https://forum.upcase.com/t/dependent-country-city-state/7038 my code is below
routes.rb
resources :states, only: :new
registrations.new.html.erb
<div class="field">
<%= f.select :state, options_for_select(CS.states(:us)), {:prompt => "State"}, {:class => "signup-input-container--input", :id => "state-picker"} %>
</div>
<div class="field">
<%= f.select :city, options_for_select([]),{}, {:class => "signup-input-container--input", :id => "city-picker"} %>
</div>
main.js
document.addEventListener("turbolinks:load", function(){
var state = document.getElementById("state-picker");
state.addEventListener("change", function() {
Rails.ajax({
url: "/states?country=" + "United States" + "&state=" +
state.value,
type: "GET"
})
})
});
registrations-controller.erb
def new
super
#cities = CS.get(:us, params[:state])
end
new.js.erb
var city = document.getElementById("city-picker");
while (city.firstChild) city.removeChild(city.firstChild);
var placeholder = document.createElement("option");
placeholder.text = "Choose a city";
placeholder.value = "";
city.appendChild(placeholder);
<% #cities.each do |c| %>
city.options[city.options.length] = new Option('<%= c %>');
<% end %>
im trying to get this to work the way the example link shows. the only difference is that users will only choose states from the US and citys
From our discussion in the comments the issue appears to be that you are requesting the wrong URL for your cities.
You have a route at /states/new but are making the request to /states. Try updating your main.js to:
document.addEventListener("turbolinks:load", function(){
var state = document.getElementById("state-picker");
state.addEventListener("change", function() {
Rails.ajax({
url: "/states/new?state=" + state.value,
type: "GET"
})
})
});
(I removed the country parameter in the URL because you don't seem to be using it, you say you only need this for the US anyway.)
Let me know how you get on with that.

How to display a selection based on user input using ajax and jquery

Think of the below as a bike rental. Someone fills out a form and gets a bike assigned to them which they can rent and borrow for a certain amount of time.
The problem I am having is I am trying to show the person who wants to rent the bikes what bikes are available before they submit the form. Below is my attempt using ajax. I have no errors but also my select is not updating.
request controller methods below
def new
#bikes = Bike.available_based_on_request_date(params[:Borrow_date], params[:Return_date])
#new_request = Request.new
end
create method below (with a temporary workaround, that reloads the form with a warning about availability.)
def create
#request = Request.new(request_params)
available_bikes = #request.new_request(current_user.id)
if (available_bikes >= #request.number_of_bikes_wanted) && #request.save
redirect_to root_path
else
flash[:warning] = "You have requested more bikes than available. There are only #{available_bikes} bikes available"
redirect_to new_request_url
end
end
params in request controller
def request_params
params.require(:request).permit(:Borrow_time, :Borrow_date,
:Return_date, :Return_time,
:number_of_bikes_wanted, bike_ids: [])
end
new.html.erb view
<div class="form" align = "center">
<%= render 'form.js.erb' %>
</div>
_form.js.erb below
<script type="text/javascript">
$(document).ready(function() {
$('.my-date').on('change', function() {
var data = {}
$('.my-date').each(function() {
if($(this).val()) {
data[$(this).attr("id")] = $(this).val();
}
});
if(Object.keys(data).length > 1) {
$.ajax({
type: "POST",
url: <%= new_request_path %>,
data: data
});
}
});
});
var options = "";
<% #bikes.each do |bike| %>
options += "<option value='<%= bike.id %>'><%= bike.name %></option>"
<% end %>
$('#request_number_of_bikes_wanted').html(options);
</script>
<div class="block-it" align=center>
<br>
<%= form_for #new_request do |request| %>
<%= request.label :Borrow_date, 'Borrow on' %>
<%= request.date_field :Borrow_date, id: 'Borrow_date', class: 'my-date', min: Date.today, :required => true %>
<%= request.label :Borrow_time, 'Borrow at' %>
<%= request.time_field :Borrow_time, value: '10:00', min: '9:00 AM', max: '4:30 PM', default: '10:00 AM', :ignore_date => true, :required => true %>
<br><br>
<%= request.label :Return_date, 'Return On' %>
<%= request.date_field :Return_date, id: 'Return_date', class: 'my-date', min: Date.today, :required => true %>
<%= request.label :Return_time, 'Return at' %>
<%= request.time_field :Return_time, value: '10:00', min: '9:00 AM', max: '4:30 PM', default: '10:00 AM', :ignore_date => true, :required => true %>
<br><br>
<br><br>
<%= request.label :NumberOfBikesWanted, 'Number of bikes' %>
<%= request.select :number_of_bikes_wanted, %w(select_bike), :required => true %>
<br>
<%= request.submit 'Submit' %>
<%= request.submit 'Reset', :type => 'reset' %>
<% end %>
<br>
</div>
There are a two main problems with your code:
Controller
Use a different action to set the endpoint that you will call with ajax, so instead of this:
def new
#bikes = Bike.available_based_on_request_date(params[:Borrow_date], params[:Return_date])
#new_request = Request.new
end
Try this:
def bikes
#bikes = Bike.available_based_on_request_date(params[:Borrow_date], params[:Return_date])
def new
#new_request = Request.new
end
If you want to keep REST routes, then create a new controller and use the index action within that controller.
Form
This code:
var options = "";
<% #bikes.each do |bike| %>
options += "<option value='<%= bike.id %>'><%= bike.name %></option>"
<% end %>
$('#request_number_of_bikes_wanted').html(options);
doesn't belong here, it must be deleted from your file and instead put it on a new file called bikes.js.erb; also rename your form to _form.html.erb.
And update your ajax call to use your new route:
$.ajax({
type: "POST",
url: <%= bikes_path %>,
data: data
});
What you want to setup is a new endpoint but instead of returning html, it will return a js. But you must treat it as an independent action, just as any other action in rails. The only difference is how you call that action (ajax) and how you respond to it (js).

Filter field based on previous field selection

How can I use simple_form to filter a field, based on a previous fields value?
For instance, I have an Opportunities form, with two fields, Company and Contact.
Company Field:
<div class="form-group">
<%= f.association :company, collection: Company.all.order(:account), prompt: "", :label_method => :account, :value_method => :id %>
</div>
Contact Field:
<div class="form-group">
<%= f.association :contact, collection: Contact.all.order(:first_name), prompt: "", :label_method => lambda { |contact| "#{contact.first_name} #{contact.last_name}" }, :value_method => :id %>
</div>
Here is what I want to do: If I select a company called "Deviant" from the Company field above, I want the Contact field to only display those contacts associated with the company called "Deviant".
I am trying something like this, but can't get it to work:
<div class="form-group">
<%= f.association :contact, collection: Contact.where("company_id = ?", params[:id]), prompt: "", :label_method => lambda { |contact| "#{contact.first_name} #{contact.last_name}" }, :value_method => :id %>
</div>
I don't know how to reference the value in the Company field.
How can I do this?
Thanks.
Update
Anyone? Surely this must be possible. This is a key functionality in any form. I would hope I don't need jQuery or something.
I think the best approach is to use ajax requests to update your contacts collection dinamically whenever the company's selected value is changed.
First you'll need an action in your contacts controller:
app/controllers/contacts_controller.rb
class ContactsController < ApplicationController
def contacts_list
if params[:company_id]
#contacts = Contact.where(company_id: params[:company_id])
else
#contacts = Contact.all
end
respond_with(#contacts) do |format|
format.json { render :json => #contacts.to_json(:only => [:id, :first_name, :last_name]) }
end
end
end
Add this to your routes:
config/routes.rb
post 'contacts_list' => "contacts#contacts_list", as: :contacts_list
Then use the coffeescript code bellow to populate your contacts' collection:
app/assets/javasctipts/companies.js.coffee
$(document).ready ->
if $("#opportunity_company_id")
populate_contacts()
$("#opportunity_company_id").change ->
populate_contacts()
populate_contacts = ->
$contacts_select = $("select#opportunity_contact_id")
$contacts_select.attr "disabled", "disabled"
company_id = $("select#opportunity_company_id").val()
if company_id is ""
$contacts_select.html "<option value=\"\">(select the company first)</option>"
else
$contacts_select.html "<option value=\"\">(loading contacts...)</option>"
data = {company_id: company_id}
data[window._auth_token_name] = window._auth_token
$.ajax "/contacts_list",
type: "post"
dataType: "json"
data: data
success: (contacts) ->
_html = '<option value="">Select the contact:</option>'
_html += '<option value="'+contact.id+'">'+contact.first_name + ' ' + contact.last_name + '</option>' for contact in contacts
$contacts_select.html _html
$contacts_select.removeAttr "disabled"
error: ->
alert 'Error trying to load contacts.'
Finally, inside your html's head tag:
<% if protect_against_forgery? %>
<script>
window._auth_token_name = "<%= request_forgery_protection_token %>";
window._auth_token = "<%= form_authenticity_token %>";
</script>
<% end %>
Hope it helps...
update:
Add the following line to your ApplicationController (app/controllers/application_controller.rb):
respond_to :html, :xml, :json, :js

Rails show index results from options_from_collection_for_select

I have a Rails app with Clients that have_many Contacts. I would like to modify the contacts/index list with a selection of the Client. So, the user selects the Client and the screen refreshes showing the Contacts for that Client.
I started with this dropdown selection:
<%= select_tag 'Client', options_from_collection_for_select(Client.all, :id, :client_name) %>
But, I'm not sure how to modify the table code that gets the Contacts:
<% #contacts.each do |contact| %>
Do I need to use jquery?
Thanks for the help!
Update1:
Could I add #selected_client to the statement:
<%= select_tag 'Client', options_from_collection_for_select(Client.order(:client_name), :id, :client_name, #selected_client) %>
Then use this:
<% #selected_client.contacts.each do |contact| %>
Here's how I'd do it, note, this isn't tested since I just typed it up in here, but it should give you a good place to start from. Post back with your code if you need more help from here on.
<%= select_tag 'client', options_from_collection_for_select(Client.all, :id, :client_name) %>
<%= select_tag "client_contacts" %>
Then you'll need some js for the ajax:
$(document).ready(function() {
$("#client").on("change", function() {
var the_id = $(this).val();
$.getJSON("/client/contacts", {id: the_id},
function(data){
var options = '';
for (var i = 0; i < data.length; i++){
options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
}
$("#client_contacts").html(options);
});
});
});
Then you'll need a route for client/contacts:
get 'client/contacts/:id', to: 'client/contacts'
controller example:
def contacts
#client = Client.find(params[:id])
respond_to do |format|
format.json { render: json: {#client.contacts.to_json}}
end
end

Dynamic Partial Based on Select Box - Rails 2.3.5

I've edited my request to hopefully be clearer. I need to render a partial dynamically based on a previous selection box.
REQUEST belongs to PRODUCT
PRODUCT belongs to CATEGORY
CATEGORY has many PRODUCTS
PRODUCT has many REQUESTS
User hits form: create_request.html.erb
User selects a category, then the products select list is populated (like Railscast 88 - dynamic select boxes)
What I now need is to render different partial forms based on which product is selected. I suck at jquery.
create_request.html.erb:
<%= javascript_include_tag "dynamic_products.js" %>
<% form_for :request, :url => {:controller => :requests, :action => :create_request, :id => params[:id]} do |f| %>
<label>Select Category:</label>
<%= select( "request", "category_id", Category.find( :all).collect { |c| [c.name, c.id] })%></br>
<div id="product_field">
<label>Select Product</label>
<%= select( "request", "product_id", Product.find( :all).collect { |p| [p.name, p.id] })%></br>
</div>
#### and here is where I need help:
#### if request.product_id = 1, render partial _form1
#### if request.product_id = 2, render partial _form2
<button type="submit">Submit</button>
<% end %>
dynamic_products.js.erb:
var products = new Array();
<% for product in #products -%>
products.push(new Array(<%= product.category_id %>, '<%=h product.name %>', <%= product.id %>, <%= product.active %>));
products.sort()
<% end -%>
function categorySelected() {
category_id = $('request_category_id').getValue();
options = $('request_product_id').options;
options.length = 1;
products.each(function(product) {
if (product[0] == category_id && product[3] == 1) {
options[options.length] = new Option(product[1], product[2]);
}
});
if (options.length == 1) {
$('product_field').hide();
} else {
$('product_field').show();
}
}
document.observe('dom:loaded', function() {
categorySelected();
$('request_category_id').observe('change', categorySelected);
});
one reminder first before we start. I'm not sure about this but I think request is a reserved word in rails.
JS
this just observes the dropdown and performs an ajax call
$(document).ready(function() {
$('#request_product_id').change(function() {
$.ajax({ url: '/products/' + this.value + '/form_partial' });
});
});
ROUTES
nothing fancy here either. Just setting up a route where the ajax will go to when it is triggered
resources :products do
get :form_partial, on: :member
end
CONTROLLER
we just fetch the product using :id which is passed from ajax
def form_partial
#product = Product.find params[:id]
end
JS TEMPLATE
you need to create a form_partial.js.erb which will render the partial depending on the product. The code below appends the partial after the product_field div
# app/views/products/form_partial.js.erb
$('#product_partial').remove();
<% if #product.id == 1 %>
$('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial1') %></div>');
<% else %>
$('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial2') %></div>');
<% end %>
UPDATE: for rails 2.x
we just need to change the routes and the js template in order for this to run on rails 2.x
ROUTES 2.x
map.resources :products, member: { form_partial: :get }
JS TEMPLATE 2.x
if I remember correctly, the file should be named form_partial.js.rjs. This will give you a page variable which you can use to add js.
# app/views/products/form_partial.js.rjs
page << "$('#product_partial').remove();"
page << "<% if #product.id == 1 %>"
page << " $('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial1') %></div>');"
page << "<% else %>"
page << " $('#product_field').after('<div id="product_partial"><%= escape_javascript render('partial2') %></div>');"
page << "<% end %>"

Resources