How does "respond_with_navigational" work? - javascript

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.

Related

Rails code for format js do not work

I'm trying to implemet a complex task, and faced with a problem, that my JS code do not work when called from format.js.
I have a link with such code:
= link_to new_user_support_letter_path, {:id => 'contact-us', :remote => true }
In my user_support_letters_controller.rb:
def new
#letter = UserSupportLetter.new
respond_to do |format|
format.js {}
format.html
end
end
In new.js.erb:
alert("rrr");
So, when I click a link nothing happens.
Meaningful logs for clicking a link:
I, [2016-10-19T21:47:41.130608 #1] INFO -- : Started GET "/user_support_letters/new" for 172.18.0.6 at 2016-10-19 21:47:41 +0000
I, [2016-10-19T21:47:41.150411 #1] INFO -- : Processing by UserSupportLettersController#new as JS
I, [2016-10-19T21:47:41.269853 #1] INFO -- : Rendered user_support_letters/new.js.erb within layouts/application (0.1ms)
I, [2016-10-19T21:47:41.344629 #1] INFO -- : Rendered application/_support_email.slim (0.1ms)
...
Can anybody tell what I'm doing wrong? Thanx!
To get this to work you need to set layout to false and declare the content_type you're using.
From what I know/have read this is standard behaviour in rails. Here is a similar post discussing it with a link to a bug log. https://stackoverflow.com/a/1170121/3366016
Change your controller action to this:
def new
#letter = UserSupportLetter.new
respond_to do |format|
format.js { render layout: false, content_type: 'text/javascript' }
format.html
end
end
By default it will try to load in the current layout for the given content type. For JS it typically is smart enough to know not to load a layout. By setting false you are disabling the layout and just telling it to render without a layout.
It seems if you are using some form of templateing it messes with the requests a bit. This answer seems to identify in the comments a specific work around for slim template. This answer describes another solution, basically using the default layout setup. With this, Rails seems to know how to handle it for JS requests.

Problems submitting AJAX request in Rails 4

I've been following http://blog.markhorgan.com/?p=522 as a guide to update an image in a form with an ajax callback. Image saves fine but I want to do some clever ajax so the page doesn't refresh.
Here's my code:
edit.html.haml:
#promo-image
= render partial: 'promo_image'
_promo_image.html.haml:
= form_for( #property, remote: true) do |f|
= f.file_field :promo_image, :pattern => "^.+?\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$", :id => 'promo-image-upload'
= f.submit 'Update'
= image_tag #property.promo_image.url(:medium)
properties_controller.rb
def update
#property = Property.find(params[:id])
if #property.update(property_params)
format.js
else
render 'edit'
end
end
update.js.haml:
$("#promo-image").html("#{escape_javascript(render partial: 'promo_image',)}");
With the code outlined above I get error pointing to the format.js line:
ArgumentError in PropertiesController#update too few arguments
Can anyone see where I'm going wrong or perhaps point me in the right direction?
Many thanks!
Steve
UPDATE
Just to be clear, I want to be able to update JUST the Div stated here:
update.js.haml:
$("#promo-image").html("#{escape_javascript(render partial: 'promo_image',)}");
This code works, but refreshes the whole page:
respond_to do |format|
format.html { redirect_to edit_property_path(#property) }
format.js
end
FURTHER UPDATE
Just to be clear on my motives, I want to be able to update an element on the edit page, and not be redirected to a different one, e.g. show or index. This is for UI reasons. The guide above talks about the exact same thing.
FINAL UPDATE
The issue is because I'm using a file upload, this can't be achieved via ajax. For those in a similar situation see here: Rails form_for with file_field and remote => true and format => :js
A solution could lay here, and I will investigate this: https://github.com/JangoSteve/remotipart
Thanks to everyone for helping me work out the error of my ways!
Regarding your first update, you said that this code works, but refreshes the page:
respond_to do |format|
format.html { redirect_to edit_property_path(#property) }
format.js
end
If that is the case, that means the incoming request is an html request, rather than an AJAX request. So the format.html block runs and redirects the browser to the same page, which now has the updated image.
What you need to do is figure out why the page is not sending the request as AJAX. You can see the request format if you look at the terminal output (if running locally). It will say something like:
Processing by ControllerName#action as [format]
Format needs to be JS in order for the format.js to render update.js.haml.
UPDATE:
Now that you mention it, the issue is indeed the file_upload field. Uploading files with AJAX is actually not possible with the Forms Helper. See the docs:
Unlike other forms making an asynchronous file upload form is not as simple as providing form_for with remote: true. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
I did a quick search on Google and found the remotipart gem, which seems to specialize in doing this. I don't have any experience with it though, so you're on your own from here on. :)
Try changing your update action to
def update
#property = Property.find(params[:id])
if #property.update(property_params)
respond_to do |format|
format.html { redirect_to properties_path }
format.js
end
else
render 'edit'
end
end
Source

Rails 3, rendering partial view through ajax

I'm making an e-mail service with mailboxer gem.
In my index view I have several links that will lead to inbox/draft... like this:
<%= link_to "Inbox", show_conversations_path, :remote => true %>
...
<div id="content">
</div>
Then my show_conversation js.erb
$("#content").html("<%=escape_javascript(render :partial=>"show_conversations")%>");
the controller (messages_controller)
def show_conversations
#inbox = current_user.mailbox.inbox
respond_to do |format|
format.js
end
end
And there's also a partial view _show_conversations.html.erb (already tested, through a simple render so no errors there).
So my problem is that, when I click on the link, it actually redirects to a blank plage (when it shouldnt, or at least it's not my intention, redirect at all, just show the content on the div).
I've realized that it actually renders its controller, then the erb.js, the partial view, and I Don't know why the controller again but this time as HTML.
A piece of the log:
Started GET "/en/messages/show_conversations"4
Processing by MessagesController#show_conversations as JS
...
Rendered messages/_show_conversations.html.erb (7962.4ms)
Rendered messages/show_conversations.js.erb (23239.0ms)
Completed 200 OK in 23330ms (Views: 23237.9ms | ActiveRecord: 5.0ms)
Started GET "/en/messages/show_conversations
Processing by MessagesController#show_conversations as HTML
Completed 406 Not Acceptable in 8ms (ActiveRecord: 0.5ms)
I know it shouldn't redirect, and I believe it shouldn't call two times to the controller (and the second one as if it was html instead of js), but I don't really know why it's happening nor have I found a similar problem through the forum
Check with below code, if it works
def show_conversations
#inbox = current_user.mailbox.inbox
respond_to do |format|
format.js { render :layout => false }
end
end
Try modifying this line:
$("#content").html("<%=escape_javascript(render :partial=>"show_conversations")%>");
to:
$("#content").html("<%= escape_javascript(render :partial=>'show_conversations') %>");
or make it pretty:
$("#content").html("<%= j render :partial=>'show_conversations' %>");

javascript and rails 3

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

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.

Categories