I have a Rails app that uses javascript (Backbone) to show user specific data on each users profile page /views/users/show.html.erb. I do this by passing <%= #user.id %> as a data parameter to Backbone's fetch function, however, the only way I know how to get the <%= #user.id %> into Backbone's fetch function is by embedding the javascript in each views/users/show.html.erb page, which therefore allows Backbone to load different user specific info for each views/users/show.html.erb page. Although this works, it seems like the wrong way to do it, as I have read that I should not embed javascript like this. Furthermore, I am going to have to do it a lot, because I wish to display a lot of different kinds of data, more than you see below. So the show.html.erb page will be filled with javascript to make the app work the way I wish.
Question: how might I get #user.id into Backbone's fetch function for each user's show page without embedding javascript in the way that I've done. In the comments, someone suggest I use app/assets/javascripts/user.js, but I don't know how to get <%= #user.id %> into that file. #user.id is readily available in show.html.erb
<script type='text/javascript'>
$(document).ready(function() {
app.collections.awardCollection.fetch({ data: $.param({ user_id: <%= #user.id %> }) }).complete(function(){
app.views.awardCollection = new app.Views.awardCollection({ collection : app.collections.awardCollection});
app.views.awardCollection.render()
});
});
</script>
In order to understand how the views works, is that you can add as many extensions to a view as you want, and they will be parsed by the right library.
If you create a view like
my_view.haml.erb
It will be first parsed with ruby (erb), and then with haml, and will end in a html page.
You can create many views for js, usually you want to archive that when you do ajax, so you can end having a js view like:
my_view.js.erb
First ruby will be parsed (all the <% %> tags), that will end as plain text, and then the server will serve the .js file. But that's usually a common task for ajax.
If you have to render a html page where you want to put some js and you need some ruby code on it, what I usually do is to put the data in the html content with a hidden div.
You can put in any view (even on your layout if you want it to be globally available), something like:
<div id="user_id" style="display: none;"><%= #user.id %></div>
And then on a js (or coffeescript or whatever) you can just check the content of that div:
<script type="text/javascript">
var user_id = $("#user_id").html();
</div>
that's really useful when you want to debug or create tests for your js files, since its plain js and won't throw syntax errors.
I see the comment of Luís Ramalho and Gon is a good option, but I recommend use the following approaches:
If the from the variable is not going to change, print it with <%= %> under .js.erb files located in app/assets/javascripts (note that it will be cached until you restart your app)
If you need server variables the best way is to use Ajax
You can define functions on .js files on app/assets/javascripts and call those functions from the views
If you really don't want any Javascript code in the view, you can create the functions on a .js on app/assets/javascripts (corresponding to the view, for order), and use events and/or store the variables in hidden fields (or even use the data attribute from HTML5)
Related
I have a checkout popup I would like to share between different pages (event, video meeting ...), so I thunk creating a shaded element /views/shared/_checkout.html.erb, and insert <%= render "shared/checkout" %> in my pages.
Uncaught ReferenceError: popup_payment is not defined
All the html and javascript is this shared page.
I just can't understand why from my pages (event, video ...) I can not call the javascript from this shared component.
the html and the javascript is present when I check the source. I was excepting that render / render partial was acting some code injection, am I wrong ?
How could I preserve the DRY - Don't repeat Yourself - in ERB ?
And have the elements / javascript communicate betweek page and included javascript ?
Here is some pseudo code example :
pageA.html.erb
<%= link_to image_tag('pinandchip.png', size: '18x18'), '#', onclick: 'popup_payment();', class: "btn flat" %>
...
view/shared/_popup.html.erb
<script>
function popup_payment() {
}
</script>
You could try adding the class payment-popup-button to your button and create a new file in app/assets/javascripts/shared called popup.js.
In that file you can do something like:
$(document).ready(function(){
$('payment-popup-button').click(function(e){
e.preventDefault();
$('#popup_payment_div').show();
});
});
This assumes that you're using jQuery, and that you've already rendered the popup code somewhere on the page, but it's hidden.
If you need to render a fresh form every time or populate the form with dynamic data you'll probably have to create controller actions that respond_to and render js.erb to get you the right markup.
It's hard to say exactly without seeing more code.
Are you ensure that your javascript function is loaded in all pages?
On this question answer how to have global javascript functions on rails projects.
i found a solution with this gem :
https://github.com/komposable/komponent
it fulfill my needs : create external components
Is it possible to call a ruby helper method from within a js.erb file?
I have a helper in application_helper.rb called solve which makes a API call to a third party service, and they only have a ruby client.
The js.erb file isn't being run on the client side, it is being called from within a controller method and run server side as it is PhantomJS.
I call the JS file from the controller
Phantomjs.run('phantom.js.erb', url)
Then within the PhantomJS js.erb file I have tried
var response = '<%= solve(variable) %>'
which just sets the variable as the string <%= solve(variable) %>
I have also tried
var response = <%= solve(variable) %>
but that just seems to make the application hang and become unresponsive.
I have seen other questions similar to this. In those questions they are asking if it is possible to call it from client side JS which I know you need to use an ajax request to do so.
Is this possible?
Try this:
var content = '#{solve()}'
Need a bit more context for this question, but I'll try my best to answer:
Essentially, you wouldn't be able to access your application_helper methods outside of any .erb files. (ie. if you have application.js or any other js file in your pipeline and you are trying to <%= solve %> from there it wouldn't work - mainly because it isn't an .erb file)
There are a lot of ways and architecture to go about solving this, but here are two simple ones:
If you put the JS you want to evaluate inline on the same page as your partial/html.erb page by using <script> //JS ERB CODE GOES HERE </script> It will actually evaluate properly since it is inside of an erb file. However, this is generally looked upon as unclean...
What you probably want to do is pass the value (presumably) you want that comes from the "solve" application_helper in a 'data' attribute on the html element that it affects. By utilizing "unobtrusive javascript" in this way, you simply pass the value through markup and then in your JS you can get the variable by using jQuery code like this. Here's an example:
<%= link_to "test_link", root_path, :data => {:solve => solve } %>
Of course it doesn't have to be a link, any HTML element will do, and then in your jQuery:
$("#test_link").data("solve");
will return to you whatever output comes out of your "solve" method in the application_helper.
it can possible but there are different ways to do it. one way is define the method in helper_method in your controller and call it from your view. and another way is use the gon gem to access some controller value in your javascript. please check what is best for you please check the below links for more help
http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method
https://github.com/gazay/gon
http://railscasts.com/episodes/324-passing-data-to-javascript
I am conducting partial caching which is working really well.
However if I change the DOM inside the cache block those changes arn't cached. Is there a way to also include those changes?
Here is what I have so far:
<%
cache(#contact.hash_key) do
%><div id="<%=#contact.hash_key%>"></div><%
end
%>
<script>
//use ajax to prepend new messages.
$(document).ready(function(){
$.get("/messages?cid=<%=#contact.hash_key%>", function(data) {
$("#<%=#contact.hash_key%>").prepend(data);
});
});
</script>
UPDATE
Ok so I am trying to attempt to cache the result before it enters the DOM with the same cache key. That way when the cache block is rendered the new data is included with that key.
But I'm not sure the correct way to structure this.
Done!
So for anyone wanting to do the same thing here is a brief outline on how to do it. You may need to make changes or tweak this solution to fit your own.
This will only work if you are using cache keys. In my instance I have 2 types. A contact.hash_key and a message.hash_key
All message caches are kept inside a parent contact cache. So essentially:
<div id='contact-hash'>
<div id='message-hash-1'>
<div id='message-hash-2'>
<div id='message-hash-3'>
First of all we need to loop through the messages and see if they are cached. If they are then you can just render the cached copy. You can do this by using the Rails.cache.read method:
messages.each do |message|
cache = Rails.cache.read 'views/'+message.hash_key
if cache.nil? == false
%><%= cache.html_safe %><%
end
end
So now we have a list of messages from cache thats already been loaded. So what about new messages? Lets load these via ajax so the user isn't waiting for a boring page load.
You will notice in my question above I have querying "/messages?cid=<%=#contact.hash_key%>" in my AJAX call. This is calling the messages controller and rendering the index view.
Before we want to load the rendered view into the DOM we want to write it to the cache first with, surprise surprise, the identical message.hash_key we are going to use to read it.
So in your view:
<%
cache(message[:hash_key]) do
%>
<div class='message'>
This is a new message from the server.
</div>
<%
end
%>
If in some situations this doesn't work (god knows theres so many app permutations out there) you can also use Rails.cache.write 'foo', 'bar' in the controller instead of caching it at the view level.
And there you have it. Now you can add the new hash_key to the list and then render the view back to the DOM as the results of your AJAX call.
Now with the new hash_key in the list you can loop over it and it will come up as a cached copy.
This may or may not be the most elegant solution. If someone wants to simplify or give any advice on it so I can improve it that would be much appreciated.
I'm currently ajaxifying my Rails app as follows.
JS
application.js
$("a").live("click", function() {
$.getScript(this.href);
//do something
return false;
});
Views
index.js.erb
$("#core").html("<%= escape_javascript(render 'index') %>");
index.html.erb
<%= render 'index' %>
_index.html.erb
#my partial
So when a user clicks a link, it will be intercepted and the corresponding js file will be executed, which renders a partial in a div. This means that, for each action, I will need 3 views, say index.js.erb, _index.html.erb, and index.html.erb.
This is painstaking to set up, and the index.html.erb file is somewhat useless, it just renders the partial (perhaps there's a way to render a full view from another view directly, hence eliminating the need for a partial?).
Is this the best way to do things? How do you usually imbricate Ajax with Rails?
Thanks.
Javascript MVC seems like it works well with MVC style backends. It standardizes ajax calls, controllers and views in a similar way that you are showing above:
http://javascriptmvc.com/
I am learning Ruby on Rails, and I am very confused on how the controller-model-view relationship works for my application.
What I have now is a table full of comments (posts) users have made. What I want to do is let users click on a comment to see more information in a separate panel (ie, other database fields that weren't initially shown, for example the user_id of the person who posted the comment).
In my _post.html.erb, I have something like:
<div class="post" id="<%= post.post_id %>" onclick = ?? >
<p>post.text</p></div>
What should go in onclick? I need a way for the onclick to call a helper/controller method which can load more information, and then put that in another div on a page (I've tried variations of using the controller and helper to call javascript which inserts html into the site, but that seems messier than it should be). From what I understand, I should create some kind of partial _postdetails.html.erb file that handles the actual displaying of the html, but I have no idea how to specific where that partial would go in the page.
Any help would be appreciated, thanks!
You can achieve what you want either by using Rails helpers or by writing the AJAX calls yourself.
Personally I manually write all my AJAX calls using jQuery.
You can also use Prototype which ships with Rails.
That being said you can do.
In your JS file :
$("div.some-class").click(function()
{
$.ajax(
{
url:"url/to/controller/action",
type:<GET>/<POST>,
data://If you wish to sent any payload
});
});
In your controller :
def some_action
#some computation
render :update do |page|
page["id_of_div_to_be_refreshed"].replace_html :partial => "some_partial"
end
end