javascript and rails 3 - javascript

Creating an update.js.erb, or edit.js.erb javascript file is connected to the rails 3 actions?
I'm new to rails 3 but know javascript.
If I add respond_to to each action to accept javascript, then will this code be called upon the action?
Thanks

Unable to understand your question, but based on what I understand you might looking for this.
You can render js files using render :js like:
render js: "$('#div_name').some_event;"

In Rails 3 you should set different respond types on the top of your controller class.
Something like this (probably it does not make any sense, but this is a dummy example):
class UsersController < ApplicationController::Base
respond_to :html
respond_to :xml, :json, :except => [ :edit ]
respond_to :js, :only => [:create]
def index
respond_with(User.all)
end
end
Then, you are responding using respond_with, and Rails will recognize type of request based on Accept header or request.format like (/users.json, /users.xml, etc.) and render proper files (index.html.erb, create.js.erb, etc.) depending on format

"Creating an update.js.erb, or edit.js.erb javascript file is connected to the rails 3 actions?" not necessarily, but it should be. conventionally, the file name should be the same as the method name. its a logical relation. but u can specify a file name(if the file name is different the method name) by
respond_to do |format|
format.js { render :action => "different_action" }
end

Related

Kaminari How to process routes as javascript

I have an issue. I had a freelancer do some things with my code and he messed up some things. One of the main things is the pagination doesn't work. I checked my old files and it used to say this
Processing by HomeController#load_more_books as JS
Now it's giving me
Processing by HomeController#load_more_books as JSON
How do I change the processing back to Javascript? Thank you
Change the default format in your routes
get "/some-resource", to: "some_controller#some_method", defaults: {format: "js"}
or in you controller you can tell .json requests to respond to .js
#app/controllers/some_controller.rb
class SomeController
def some_method
respond_to do |format|
format.json { render "some_js_template.js" }
end
end
end

Cucumber Testing js.erb functions when no html.erb exists

My rails application is using js.erb views instead of html.erb views for specific windows. This works fine in practice, but when I'm using cucumber tests with capybara it gives me an error of
Missing template admin/groups with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths
When I click the button pertaining to this particular view. There is no groups.html.erb but there is a groups.js.erb. I want to somehow tell cucumber/capybara to not try to render the groups.html.erb but still render the groups.js.erb. I would prefer not to generate an unnecessary html file to render the same thing the escape javascript below is doing.
groups.js.erb:
$("#admin_content").html("<%= escape_javascript(render :partial => 'groups') %>");
Relevant admin controller method:
def groups
#groups = Group.all
end
You should use proper MIME type handling for your responses. Try this:
def groups
#groups = Group.all
respond_to do |format|
format.js
end
end
eventually you can be more specific about how to respond :
format.js { render layout: false }
more info on respond_to here.
note: if your controller only manages js responses, you can add respond_to :js at the top of the class, and then use respond_with #object in your actions.

Query rails database, and update highcharts using Javascript

I have a page which shows a highchar. I'd like to use Javascript to fetch several pieces of information for a specific user. I want to fetch from my database and place it on the highcharts graoh. I have set up a JSfiddle which shows static data. But
What I am trying to do is:
Make javascript call a Rails action with parameters.
Query the rails database(projectHours table).
Rails returns the response.
Javascript updates highcharts and maps the information stored in the projectHours table.
So my question is What if I want to use information from my db?
Two of the following models
Effort.rb
class Effort < ActiveRecord::Base
belongs_to :project_task
belongs_to :user
end
Users.rb
class User < ActiveRecord::Base
has_many :projects
has_many :efforts
A further note, I think that in my efforts controller I may need to add some form of render action
rails reponds_to do |f| f.json
{ render :json => some_hash
}
end
You can use jQuery's get function in order to send a GET request to your rails app like so
$.get("/efforts/24", { name: "John", time: "2pm" } );
And in your controller you could do something like
def show
#effort = Effort.find(params[:id])
# or find by some of the name of time params
respond_to do |f|
format.json { render :json => #effort }
end
end
Depending on how you want to render the results you can either let javascript handle the ajax:success by adding in to the original jQuery get
$.get("/efforts/24", { name: "John", time: "2pm" } ).success(function(data) {
alert(data)
// Or do whatever you want :)
});
Or you can change the respond_to to
respond_to do |f|
format.html { render :nothing => true }
format.js
end
And create a show.js.erb in your app/views/efforts directorty. In this file you can use the responded object
$('body').html("<h1><%= escape_javaScript(#effort.title) %></h1>").append("
<%=escape_javaScript(#effort.content) %>");
Some good tutorials
Rails and jQuery
jQuery GET

How does "respond_with_navigational" work?

I'm working with Devise and DeviseInvitable to manage authentication in my app and I'm having some trouble adding AJAX support to InvitationsController#update. The controller in DeviseInvitable looks like this:
# invitations_controller.rb
# PUT /resource/invitation
def update
self.resource = resource_class.accept_invitation!(params[resource_name])
if resource.errors.empty?
set_flash_message :notice, :updated
sign_in(resource_name, resource)
respond_with resource, :location => after_accept_path_for(resource)
else
respond_with_navigational(resource){ render_with_scope :edit }
end
end
This works well when resource.errors.empty? == true and we execute:
respond_with resource, :location => after_accept_path_for(resource)
(i.e. invitations/update.js.erb is rendered and my javascript calls are made). The problem is that when resource.errors.empty? == false, and we execute:
respond_with_navigational(resource){ render_with_scope :edit }
the server says:
Rendered invitations/update.js.erb (1.4ms)
but my javascript calls are not being run. Can anyone explain what respond_with_navigational is supposed to be doing? I've been googling for hours and I haven't found an explanation of this api anywhere.
Thanks!
OK, I figure out what respond_with_navigational is doing. It's defined in the Devise base classes as such:
def respond_with_navigational(*args, &block)
respond_with(*args) do |format|
format.any(*navigational_formats, &block)
end
end
and, navigational_formats is defined in Devise as well:
# Returns real navigational formats which are supported by Rails
def navigational_formats
#navigational_formats ||= Devise.navigational_formats.select{ |format| Mime::EXTENSION_LOOKUP[format.to_s] }
end
So, it's basically a wrapper for respond_with(). In order to get this to work, I had to add the following to my InvitationsController:
respond_to :html, :js
and now, update.js.erb is being rendered properly.

Accessing a Ruby on Rails object in a Google Maps javascript

I am trying to access a field in a Ruby on Rails object from my view inside some JavaScript. Here is the relevant code in my view pick.html.erb:
var directionDisplay;
var start = <%= #route.from %>;
var end = <%= #route.to %>;
From and to are text fields that hold zipcodes. Here is my relevant Route controller code:
class RoutesController < ApplicationController
# GET /routes/1/pick
def pick
#routes = Route.find(params[:id])
end
I read somewhere that I need to use ActiveSupport::JSON in order to access an object field...Do I need to do this instead? If so, how do I install it and could you possibly give me an example on how to get started? I've been searching for examples everywhere the past few days and I can't find any.
Let me know if you need any more code and thank you in advance for any reply!
The file name should be (according to convention) pick.js.erb and not pick.html.erb based on the fact that you have JavaScript code included.
If you want to include a partial inside this one, you can use the escape_javascript helper to render the partial.
If you have more than one possible file to be rendered from the pick action, you should look into using respond_to such as:
#route = Route.find(params[:id])
respond_to do |format|
format.html
format.js { render :js => #route }
end

Categories