Rails with Ajax. Getting data from a model to show - ruby-on-rails

I am just starting out with Rails and Ajax and I am facing some problems integrating Ajax and Jquery.
I have data which I want to display and update in my div using jQuery.
I have written in Jquery a table where I can drag and drag items.
Right now I am using default items. I want to retrieve this items with back end rails but I am not too sure about how I could do it.
This is the model. I want to show these in the table.
class SlotAllocation < ActiveRecord::Base
attr_accessible :group_index, :lesson_type, :timeslot_id
def as_json(options={})
{
:group_index =>self.group_index
:lesson_type =>self.lesson_type
:timeslot_id =>self.timeslot_id
}
end
This is the controller actions. I've added format.js to the index and update functions.
def index
#slot_allocations = SlotAllocation.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #slot_allocations }
format.js{ render :json => #slot_allocations }
end
end
def update
#slot_allocation = SlotAllocation.find(params[:id])
respond_to do |format|
if #slot_allocation.update_attributes(params[:slot_allocation])
format.html { redirect_to #slot_allocation, notice: 'Slot allocation was successfully updated.' }
format.json { head :no_content }
format.js { head :ok}
else
format.html { render action: "edit" }
format.json { render json: #slot_allocation.errors, status: :unprocessable_entity }
format.js { render :js => #slot_allocation.errors, :status => :unprocessable_entity }
end
end
end
In the view I have a table. It is working according to some default values I have placed in.
<table id='subjects' border="1">
<tbody></tbody>
</table>
Now I want to change these default values to the values I have in rails.
By trying to piece together certain info I got from codes from github.
I tried out this.
slots= {
url: '/slot_allocations'
}
To aid in my understanding I did something like that in JQuery just to see what information I could retrieve and it turns out that I get [object Object].
TryDiv(slots);
function TryDiv(slots){
var div = document.getElementById('tryout');
div.innerHTML = div.innerHTML + slots;
}
I am not too sure what is contained in that object and would appreciate it if someone could help me out on how I could retrieve the information I need from the model.
Any articles or code samples I could refer to would be appreciated as well.

Related

Rails follow href path instead of redirect_to in controller

In my Rails app I have a modal that pops up for anytime a student is clicked to be edited. Before it redirects to the edit page, the user must provide a rationale and name for the edit being made (this information is saved in another database). However, on the confirm button in the modal I assign the href value throuh jQuery and want the page to be redirected there upon click, but it follows the path defined in the rationale_controller.rb redirect_to clause. Is there a way I can have it follow the HREF attribute instead?
All help is appreciated, thanks!
EDIT:
Modal button: <button class="btn btn-warning" id="editStudentConfirmBtn">Edit</button>
JS to assign HREF:
var kid_id = $(this).data('id');
$("#editStudentConfirmBtn").attr("href", "/kids/" + kid_id + "/edit");
Default rational_controller.rb setting:
def create
#rationale = Rationale.new(rationale_params)
#rationale.user = current_user
respond_to do |format|
if #rationale.save
format.html { redirect_to #rationale, notice: 'Rationale was successfully created.' }
format.json { render :show, status: :created, location: #rationale }
else
format.html { render :new }
format.json { render json: #rationale.errors, status: :unprocessable_entity }
end
end
end
EDIT 2:
Modal
The solution required an AJAX call that would redirect the page to a specified location after the create action was executed.
I had to change the controller for Rationale as follows:
def create
#rationale = Rationale.new(rationale_params)
#rationale.user = current_user
respond_to do |format|
if #rationale.save
format.html { render :nothing => true }
format.json { render :show, status: :created, location: #rationale }
else
format.html { render :new }
format.json { render json: #rationale.errors, status: :unprocessable_entity }
end
end
end
And changed the JS as follows instead of assigning a href to the button using jQuery I just used an AJAX call to redirect the page automatically:
$('#editStudentConfirmBtn').click(function(){
$.ajax({
success: function(result) {
location.href = '/kids/' + kid_id + '/edit'
}
});
});

Fetching JSON Data from Facebook Graph URL in Rails

i have a ruby on rails 3.2.13 app, and i want to fetch data from my facebook page and show it one of my views...
What steps should i follow to do this?
What has to go in my controller and model and also in my view?
Please Help! ive been investigating on how to do this for like a week now, and i cannot find a good tutorial on how to get this done.
I have made a Data scaffold with the stuff i want to read from facebook.
This is my controller
class DatosController < ApplicationController
# GET /datos
# GET /datos.json
def index
#datos = JSON.parse("http://graph.facebook.com/iscopeapp")
respond_to do |format|
format.html # index.html.erb
format.json { render json: #datos }
end
end
# GET /datos/1
# GET /datos/1.json
def show
#dato = Dato.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #dato }
end
end
# GET /datos/new
# GET /datos/new.json
def new
#dato = Dato.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #dato }
end
end
# GET /datos/1/edit
def edit
#dato = Dato.find(params[:id])
end
# POST /datos
# POST /datos.json
def create
#dato = Dato.new(params[:dato])
respond_to do |format|
if #dato.save
format.html { redirect_to #dato, notice: 'Dato was successfully created.' }
format.json { render json: #dato, status: :created, location: #dato }
else
format.html { render action: "new" }
format.json { render json: #dato.errors, status: :unprocessable_entity }
end
end
end
# PUT /datos/1
# PUT /datos/1.json
def update
#dato = Dato.find(params[:id])
respond_to do |format|
if #dato.update_attributes(params[:dato])
format.html { redirect_to #dato, notice: 'Dato was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #dato.errors, status: :unprocessable_entity }
end
end
end
# DELETE /datos/1
# DELETE /datos/1.json
def destroy
#dato = Dato.find(params[:id])
#dato.destroy
respond_to do |format|
format.html { redirect_to datos_url }
format.json { head :no_content }
end
end
end
This is my Model
class Dato < ActiveRecord::Base
attr_accessible :likes, :name, :talking_about_count
end
this is the facebook json link i want to parse and show some fields of it in my view.
When i access the index of this controller im getting an error : "Unexpected Token at:http://graph.facebook.com/iscopeapp"
http://graph.facebook.com/iscopeapp
Please help!
Thank you in advance!
You could use Koala:
Koala is a Facebook library for Ruby, supporting the Graph API (including the batch requests and photo uploads), the REST API, realtime updates, test users, and OAuth validation

Weird route behaivor for show view

I am making an application with all the model names in spanish. I am having some strange issues related with the singularization.
My model:
class Artista < ActiveRecord::Base
attr_accessible :fecha, :foto, :instrumento, :nombre
end
My model name is "artista" (artist) in singular.
Controller:
class ArtistasController < ApplicationController
# GET /bandas
# GET /bandas.json
def index
#artistas = Artista.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #artistas }
end
end
def show
#artista = Artista.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #artista }
end
end
def new
#artista = Artista.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #artista }
end
end
def edit
#artista = Artista.find(params[:id])
end
def create
#artista = Artista.new(params[:artista])
respond_to do |format|
if #artista.save
format.html { redirect_to #artista, notice: 'Artista was successfully created.' }
format.json { render json: #artista, status: :created, location: #artista }
else
format.html { render action: "new" }
format.json { render json: #artista.errors, status: :unprocessable_entity }
end
end
end
def update
#artista = Artista.find(params[:id])
respond_to do |format|
if #artista.update_attributes(params[:banda])
format.html { redirect_to #artista, notice: 'Artista was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #artista.errors, status: :unprocessable_entity }
end
end
end
def destroy
#artista = Artista.find(params[:id])
#artista.destroy
respond_to do |format|
format.html { redirect_to artistas_url }
format.json { head :no_content }
end
end
end
(All this has been automatically created with the rails generate commands)
Now, my routes include the following:
resources :artistas
When I access localhost:3000/artistas everything works great. I can see the list of already created aritsts. Now, when I click on an existing artist (or after I try to create a new one, being redirected to the show artist page) for some strange reason it goes to http://localhost:3000/artistum.3 (3 being the id of the artist I clicked on). The output for that url is a completely blank page.
I have never even typed the word artistum. I don't know where it got it from. Besides, it has a dot instead of a slash to separate the name from the id, so i dont know how to redirect it.
I ran a grep search of the folder containing everything and the word artistum exists only in log files.
My guess is that somehow part of my application thinks "artista" is plural and "artistum" is its singular form.
I added to my routes match '/artistum' => 'artistas#index'and that works for the index page, but the dot has me confused on how to do it for the show pages.
Can someone help me A) find out why its trying to get there or b) how to route from those show pages?
Thanks!
You could try this:
Add this to the inflections.rb in the config/initializers folder:
ActiveSupport::Inflector.inflections do |inflect|
inflect.plural 'artista', 'artistas'
inflect.irregular 'artista', 'artistas'
end

Rails3 responding with js after json update

using http://blog.bernatfarrero.com/in-place-editing-with-javascript-jquery-and-rails-3/
The gem uses json to update, but how can I trigger my update.js.erb to update the different parts of my pages?
EDIT
Using this in an invoice page. every item in the invoice has a price field that can be updated with best_in_place.
I need to update the Total Price for line item and amount due for invoice only after field has been updated successfully.
Ended up with something like:
respond_to do |format|
if #item.update_attributes(params[:item])
format.html { redirect_to order_url(#item.order_id), :notice => "Successfully updated item." }
format.js { }
format.json { head :ok }
Edited best_in_place.js line #175
loadSuccessCallback : function(data) {
this.element.html(data[this.objectName]);
// Binding back after being clicked
$(this.activator).bind('click', {editor: this}, this.clickHandler);
if(this.objectName == "item") $.getScript('update.js'); // If its an item, call update.js.erb
},
I wanted to do the exact same thing with best_in_place pcasa. In the current version (1.0.2), the loadSuccessCallback function triggers an ajax:success event. That allows you to do this in your application.js:
$('.best_in_place')
.best_in_place()
.bind('ajax:success', function(e) {
// do your post-json call magic
});
You don't need a view update.js.erb. As ezkl already pointed out, you need to set the respond_to of your controller to json. In addition, you need to activate best-in-place in your public/javascripts/application.js
$(document).ready(function() {
jQuery(".best_in_place").best_in_place()
});
and add it in your view:
<td><%= best_in_place task, :name, :type => :input, :nil => "Click to edit" %></td>
I have a tutorial on Ajax with Prototype and JQuery on my own site - and the JQuery Part uses best-in-place: http://www.communityguides.eu/articles/15
Have you tried something along the lines of:
def update
#user = User.find(params[:id])
respond_to do |format|
if #user.update_attributes(params[:user])
format.html { redirect_to(#user, :notice => 'User was successfully updated.') }
format.json { head :ok }
format.js
else
format.html { render :action => "edit" }
format.json { render :json => #user.errors, :status => :unprocessable_entity }
end
end
end
I haven't tested this with the code in the tutorial, but the idea is that you have to tell the controller method to load the Javascript file. I'm not sure how this will interact with the redirect, but the principle is correct.

Where do I insert my Rails URL in the JQuery Autocomplete to reference the data set I want?

Where do I reference my controller (Rails) URL to show the dataset that I want in the autocomplete via JQuery? Here is my head:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/lib/jquery.bgiframe.min.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/lib/jquery.dimensions.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
Trying to figure out how to reference my controller or model (whichever I should) to get only records that are associated with a specific user_id. Just some frame of reference.
I have three tables, Users, Prospects, and Notes. Trying to set it up so that a specific user (user_id) can "add a note" and then use an autocomplete field to help "tag" to a prospect they have previously entered. I have already set up authentication and it is all working. JQuery seems to be getting me the closest. The head is above, and also I have uploaded jquery-1.3.2.js (though no reference to it yet as you can see in the head). Here is my prospects controller code:
class ProspectsController < ApplicationController
before_filter :login_required
# GET /prospects
# GET /prospects.xml
def index
#prospects = current_user.prospects
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #prospects }
end
end
# GET /prospects/1
# GET /prospects/1.xml
def show
#prospect = current_user.prospects.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #prospect }
end
end
# GET /prospects/new
# GET /prospects/new.xml
def new
#prospect = Prospect.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #prospect }
end
end
# GET /prospects/1/edit
def edit
#prospect = current_user.prospects.find(params[:id])
respond_to do |format|
format.html # edit.html.erb
format.xml { render :xml => #prospect }
end
end
# POST /prospects
# POST /prospects.xml
def create
#prospect = current_user.prospects.create(params[:prospect])
respond_to do |format|
if #prospect.save
flash[:notice] = 'Prospect was successfully created.'
format.html { redirect_to(#prospect) }
format.xml { render :xml => #prospect, :status => :created, :location => #prospect }
else
format.html { render :action => "new" }
format.xml { render :xml => #prospect.errors, :status => :unprocessable_entity }
end
end
end
# PUT /prospects/1
# PUT /prospects/1.xml
def update
#prospect = current_user.prospects.find(params[:id])
respond_to do |format|
if #prospect.update_attributes(params[:prospect])
flash[:notice] = 'Prospect was successfully updated.'
format.html { redirect_to(#prospect) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #prospect.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /prospects/1
# DELETE /prospects/1.xml
def destroy
#prospect = Prospect.find(params[:id])
#prospect.destroy
respond_to do |format|
format.html { redirect_to(prospects_url) }
end
end
end
There's always Ryan Bate's Railscast on that subject. He's using the standard Rails autocomplete.
However, I prefer to use jQuery. I've used Dylan Verheul's autocomplete recently and found it very easy to set up.
try jquery autocomplete. i don't know anything about rails, but what you need to return to autocomplete should be easy enough even for a beginner.

Resources