Ruby on Rails - modifying part of embedded Ruby in .js.erb - javascript

I'm working on a single-page site and have gotten the ajax loading of templates to insert into the content part of the site working. However, I'm having trouble doing this with multiple templates, using a parameter.
I have 5 templates, shared/blog, shared/projects, etc.
In my controller, I'm doing an AJAX call to 'replace'
pages = ['blog', 'projects', 'resume', 'gallery', 'contact']
def replace
#content = params[:content]
if not pages.include? content
content = 'blog'
end
respond_to do |format|
format.js
end
end
In replace.js.erb, I have this code:
$(".content_inner").html("<%= j render(:partial => 'shared/blog') %>");
I have kept it just saying 'shared/blog' because it works for loading the blog if I keep the embedded Ruby static like that. However, I can't figure out how to replace the 'blog' part of 'shared/blog' in here to whatever is in the #content variable. I've tried things like #{content}, but to no avail.
(It does receive the content variable correctly, the issue is just with using it)
Any help would be appreciated!
Thanks.

String interpolation requires double quotes. You're after:
$(".content_inner").html("<%= j render("shared/#{#content}") %>");
A few notes:
The :partial => hasn't been necessary for years in Rails. Just use render <partial_name>.
Rails already comes with a place to store your shared partials: app/views/application. You should move your shared partials there, and then you can render them simply by using render(#content). This is important to how Rails works, because it allows you to override the partial in controller-specific view paths. For example, calling render("blog") will render app/views/<controller_name>/blog.js.erb if it exists, and then fallback to app/views/application/blog.js.erb otherwise.

Related

Rails & AJAX, is there a reason you shouldn't render html view directly in controller action for ajax to process?

The classic way to work with Rails & Ajax is always something that looks like this:
// JS - let's assume this submits to dummies#create
$(form).submit()
# Dummies Controller
def create
#dummy = Dummy.new(dummy_params)
respond_to do |format|
format.js
end
end
# /views/dummies/create.js.erb
$("page").append("<%= escape_javascript(render partial: 'dummy_view' ) %>");
# /views/dummies/_dummy_view.html
<h1><%= #dummy.name %></h1>
I've always been curious, because the above seems to create a random create.js.erb file with very little meat... is there a reason (e.g., it's terrible convention, or terribly insecure or whatever), why you should NOT instead just render the view directly back to ajax?
// JS - basically takes responsibilites of create.js and puts it into the always
$.ajax(...).always(function(xhr, status){
$("page").append($(xhr['responseText']))
// responseText contains the partial rendered by the controller action
})
# Dummies Controller
def create
#dummy = Dummy.new(dummy_params)
render partial: 'dummy_view'
end
# /views/dummies/_dummy_view.html
# unchanged
<h1><%= #dummy.name %></h1>
NOTE above is pseudo-code, apologies for minor errors. The conceptual idea & question remain unchanged, though.
The create.js.erb is not random, is the view for the action with the expected format.
Generally, you may not have a view so simple (You may have different selectors other than "page", you may have some extra js code to be executed after or before the append), a js view/script is the general solution for an ajax request to give the response full control over what to do.
You could have what you want, but it will just work for your particular case when the selector is always "page" and you only want to append html to that element. Nothing prevents you from doing that (though you might want to use a custom ajax request and not rails' one since it sets js format by default and executes the response's script).
The convention is that a rails' remote request renders a js script, you can move out of the convention if you want. You'll lose a lot of flexibility with your approach as is (like... what if the create action fails an you need to display errors?).

Ruby ajax call initiates unwated Popup Box

I have an AJAX call for one of my routes in my Ruby on Rails project. It calls a method in a Ruby Controller to update flags on several of my objects, and then I need the page to reload to reflect those changes. This was my solution, at the end of the Ruby method:
respond_to do |format|
format.js {render js: "window.location = '#{processed_items_path(params)}'" }
end
This does exactly what I need it to do, it refreshes the page and pulls the user back to the top to see a flash notice. However, before doing so, it pops up a window that says:
The page at localhost says:
"window.location = '#{processed_items_path(params)}'"
And it requires you to click "OK" before you can continue on. Is there any way to get rid of that box?
According to the comments above, instead of redirecting it'll be better to just render your partial containing your table
I'm assuming your ajax call is working (as it's taking you to your method). For rendering your partial you can do:
def your_method
#your logic of updating attributes
respond_to do |format|
format.js {} # this will let rails look for a file named your_method.js.erb in your view
end
end
Now you simply need to render your partial in your_method.js.erb
$("#some_id_of_parent_element").html("<%=j render partial: "partial_containing_table", locals: { :your_local => partial_local} %>");
For details refer to Working with javascript in rails

How can I render via CoffeeScript in Ruby on Rails 4

I was trying to solve this problem for a while with no result.
I've wanted to pass variables and load a render into a div using CoffeeScript in rails 4.
(I'm using SpreeCommerce platform).
view:
<%= link_to taxonomy.name,root_path+'t/'+tid, {class: "uno", remote: true} %>
controller:
respond_to do |format|
format.html
format.js # menu.js.coffee.erb
end
menu.js.erb.coffee:
$('div#productos').html("<%= escape_javascript(render :partial => /shared/products) %>")
I'd like to load the page '_products.erb.html' and the partial processes the variables that I give it. As soon as I know, view and controller are ok, the problem is in menu.js.erb.coffee
Any help will be apreciated!
ADDITIONAL:
I've modified the extension to .js.coffee.erb. When I try to run the app, it shows me:
"undefined method `render' for #<#:0xa70317c>"
I tryied using <%= raw escape_javascript( render :partial =>... almost always "render" method give me problems.
NEW INFO:
I added gem 'coffee-script' to the Gemfile (then 'bundle install').
Now, when I click the link_to, it shows me into the HTML <%= escape_javascript(render :partial => /shared/products) %> as a text instead of loading the "partial"... any suggestion please?
I wrote a post about this after struggling through the same problem.
You need to:
Name it menu.js.coffee. Suffixing .erb causes it not to be evaluated as CoffeeScript.
Use raw to escape it.
I used these two on my website. Here's how it looks:
<%= raw render 'path/to/menu.js.coffee' %>
It still processes ERB within your CoffeeScript.
I would recommend changing it from menu.js.erb.coffee to menu.js.coffee.erb.
Rails will process the file extensions from right to left. Meaning right now, your file is treated first as coffeescript, then as ruby, and finally as javascript. It looks like you want to make the ruby substitutions first, then parse the coffeescript into javascript, so that would be menu.js.coffee.erb
First of all, you should change file name from menu.js.erb.coffee to menu.js.coffee.erb and you need configuration file as follow, which is a contribution by cervinka on coffee-rails issue #36
config/initializers/coffee_erb_handler.rb
ActionView::Template.register_template_handler 'coffee.erb', Coffee::Rails::TemplateHandler # without this there will be template not found error
class ActionView::PathResolver < ActionView::Resolver
EXTRACT_METHODS = %w{extract_handler_and_format_and_variant extract_handler_and_format} # name for rails 4.1 resp. 4.0
method_name = EXTRACT_METHODS.detect{|m| method_defined?(m) || private_method_defined?(m)}
raise 'unknown extract method name' if method_name.nil?
old_method_name = "old_#{method_name}"
alias_method old_method_name, method_name
define_method(method_name) do |path, default_formats|
self.send(old_method_name, path.gsub(/\.js\.coffee\.erb$/, '.js.coffee'), default_formats)
end
end

How to improve speed execution of coffeescript in rails?

To increase speed of page loading I`ve implemented creation comments via AJAX. It is simple and not heavyweight.In controller action I have:
def create
#comment = #commentable.comments.new(params_comment)
respond_to do |format|
if #comment.save
flash.now[:notice] = "Your comment added."
#response = {comment: #comment, model: #commentable}
format.js { #response }
format.html { redirect_to #commentable }
else
format.js { render nothing: :true, status: :not_acceptable }
format.html { redirect_to #commentable, status: :not_acceptable }
end
end
end
and js file:
$("<%= escape_javascript( render 'comments/comment', #response)%>").appendTo(".comments").hide().fadeIn(500)
$('.notice-wrapper').html("<%= j(render partial: 'shared/notice') %>")
$('.alert').fadeOut(3000)
if $(".no-comments").css("display") is 'block'
$(".no-comments").hide()
$(".new_answer").hide()
$(".open").show()
But instead of speed up performance I got the opposite effect. Response time through JavaScript increased on 100-200 ms(~300ms total). Is this normal behavior or I am doing something wrong? Is there any way to improve speed little bit?
My performance test:
UPD:
My performance test with just JS file.
Let's put aside for the moment my opinion that embedding ERB in CoffeeScript is utterly gross to look at and unmaintainable. It is indisputable that there's a huge performance impact when you generate and compile CoffeeScript on every request.
You also lose any chance at HTTP caching.
My first suggestion would be to separate CoffeeScript from ERB. Populate hidden fields in your ERB with the data you need, and then mine those fields in your CoffeeScript.
But if you must embed ERB in what should be static files, embed the ERB tags in pure JavaScript instead, and let the compiled CoffeeScript use those.
The code you've written wouldn't really be expected to speed up the request, because Rails still need to process all the ERB etc. You're still returning rendered HTML and sending it to the browser where it is added to the DOM.
If you wanted to make it 'faster' you could simply render the #response as json and deal with it on the client using jQuery or a front end framework.
The code does make it nicer for the user, however, because it doesn't refresh the entire page.
My suggestion would be to hook into the form request, and on success, render the new comment, else re-render form with errors. An example:
# app/javascripts/comments.coffee
$('#comment-form').bind 'ajax:complete', (data, status, xhr) ->
// psuedo code
1. if status is success
append comment -- $('#comments').append(data.comment)
2. else
re-render form with errors -- $('#comment-form').html(data.form)
Return comment template (comments/comment) and append to comments
Update your controller to return the form with JS response if not_acceptable.
Note the file is found in app/javascripts/comments.coffee

Rails render JS partial printing code to page

I'm using AJAX in my Rails app to render a JS error message when needed. It was working initially, but now coming back to it some time later, it still shows the JS error message but for some reason it now also prints the entire JS file as HTML in the window. This is what's called in the controller:
respond_to do |format|
format.js { render :partial => 'error' }
end
My file named _error.js.erb contains some JS which isn't relevant as regardless of what it contains Rails prints it to the window still.
This is what the JS looks like outputted to the window: (I tried commenting out the JS to see if it made a difference)
You can try it with some modification :
respond_to do |format|
format.js
end
Inside the action and in the view action_name.js.erb write your js code ar if you want to put your erb then use escape_javascript.
Check the following link :
Why escape_javascript before rendering a partial?
I did it! In case there will be someone else wondering a few years later, there's the answer: you should put rendered value in a javascript_tag inside your html.erb. Like this:
javascript_tag render: 'error'
that will put what rendered between <script>...</script> tags and escape all unnecessary code.
Here's the documentation on it

Categories

Resources