Dynamic Partial Based on Select Box - Rails 2.3.5 - ruby-on-rails

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 %>"

Related

Using js.erb in 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'));
});
});

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');
}
}
})
}

Rails: passing an instance variable to different controller through a partial

In Category view I have:
<ul>
<% #category.subcategories.each do |subcategory| %>
<li>
<h6>
<%if subcategory.has_topic_headings? %>
<%= link_to subcategory.name, { controller: 'subcategories',
action: 'show_topic_headings',
category_id: subcategory.category_id,
id: subcategory.id
}, data: 'topic_heading_link',
remote: true %>
<% else %>
<%= link_to subcategory.name, subcategory %>
<% end %>
</h6>
<hr>
</li>
<% end %>
</ul>
In application.js:
/* slides in the subcategory menu or the content */
$('.category-menu a').on(
'click',
function(e) {
if ($(this).attr('data')) {
/* make submenu visible */
$('.stretched.nav.row > .slider').animate({left:'-62.5em'});
e.preventDefault();
}
else {
/* make content visible */
$('.stretched.main.row > .slider').animate({left:'-62.5em'});
e.preventDefault();
}
}
);
In subcategories_controller.rb
def show_topic_headings
respond_to :js
#subcategory = Subcategory.find(params[:id])
end
And in subcategories/show_topic_heading I have:
$('.subcategory-menu').html( "<%= escape_javascript( render( partial: "layouts/topic_headings", locals: { subcategory: #subcategory} ) ) %>" );
Clicking on the active link, .subcategory-menu should be populated with the correct content and the div containing should slide in. But the content only appears if it's static (for example, if I put a string instead of a reference to #subcategory). Please note that the view in which I am inserting the subcategory partial is a category view.
The problem lies in the subcategories_controller:
respond_to, not the function itself, generates the partial. Therefore the instance variable needs to be declared before calling respond_to
def show_topic_headings
#subcategory = Subcategory.find(params[:id])
respond_to :js
end

Using an AJAX call to update a rails page without a refresh?

I have a page on my site that lets users respond to invites by either accepting or declining them.
Their response is stored in the database as the boolean 'accepted', and is used to apply the classes 'selected' or 'not_selected' (selected makes the text orange) to the 'attending' div or the 'not attending' div.
<% #going, #not_going = invite.accepted ? ['selected','not_selected'] : ['not_selected','selected'] %>
<%= link_to(outing_invite_accept_path( { :outing_id => invite.outing_id, :invite_id => invite.user_id } )) do %>
<div class="attending_div <%= #going %>">
attending
</div>
<%end %>
<%= link_to(outing_invite_decline_path( { :outing_id => invite.outing_id, :invite_id => invite.user_id } )) do %>
<div class="attending_div <%= #not_going %>">
not attending</div>
</div>
<% end %>
When either div is clicked, it's diverted to the appropriate controller actions:
def invite_accept
#outing = Outing.find(params[:outing_id])
#invite = OutingGuest.find_by_outing_id_and_user_id(params[:outing_id], params[:invite_id])
#invite.update_attribute(:accepted, true)
redirect_to({:action => "index"})
end
def invite_decline
#outing = Outing.find(params[:outing_id])
#invite = OutingGuest.find_by_outing_id_and_user_id(params[:outing_id], params[:invite_id])
#invite.update_attribute(:accepted, false)
redirect_to({:action => "index"})
end
And as right now, this code works just fine. But it requires the index page be refreshed for it to take effect.
I know it's possible to update the page without a refresh using a jQuery ajax call attached to a listener on the appropriate div, but I have no idea what such a call would look like, or where to start, really...
You want to use rail's link_to :remote => true.
See http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
For dealing with callbacks you can bind to certain events that will trigger. For example:
<%= link_to "Click Me!", some_path, :class => 'ajax', :remote => true %>
<script>
jQuery(function($) {
$("a.ajax")
.bind("ajax:loading", console.log('loading'))
.bind("ajax:complete", console.log('complete'))
.bind("ajax:success", function(event, data, status, xhr) {
console.log(data);
})
.bind("ajax:failure", function(xhr, status, error) {
console.log(error);
});
});
</script>
This page is also a pretty good write up: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

Parameter in AJAX request

I have a view which contain multiple links:
<% a.each do |q| %>
<%= link_to "stock it",
{ :action => "stock",
:qid => q.question_id,
:qur => q.question_answers_url,
:qti => q.title } ,
:remote => true %>
<div id="<%= "stock" + q.question_id.to_s %>"></div>
<% end %>
Each link generate AJAX-request. Here is a controller:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
respond_to do |format|
format.js { render :layout=>false }
end
end
Now return to the view. Each link has a 'div' with unique id='stock'. When user press the link I need to add text to specific div with corresponding id.
I have a stock.js.erb file:
$("#stock<number>").html("some text");
How can I pass div-id to stock.js.erb and how can I use it ?
Common use is to add object.id to your DOM id. That what you exactly did:
<div id="<%= "stock_#{q.question_id}" %>"></div>
Then in your controller you shoud define your question_id or your exact question:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
#question_id = params[:qid]
end
Now it will be shared with your stock.js.erb file:
$("#stock_<%= #question_id %>").html("some text");

Resources