Rails helper method seems to be killing my JQuery script - javascript

My application allows a user to make a list with different categories. While making a list, if the user decides they would like another category, they may create one without leaving the page. The new category will appear in the list, and the user can begin adding items to it.
My issue seems to be that adding any Rails helpers (link_to, render) to my 'new.js.erb' file, it stops the script from doing it's thing. My new div and dropdown menu are not rendered. I get no errors on the console or the server logs. Just nothing. If I remove these methods, everything works fine.
function addCategory(){
var lastCategory = '<%= current_user.categories[-2].name %>';
console.log(lastCategory);
$('#' + lastCategory).after("<h3 class='category'><%= #category.name %></h3>\
<div class='dropdown-button' data-toggle='collapse' data-target='#<%= #category.name %>'>\
<span class='glyphicon glyphicon-chevron-down'></span>\
</div>\
<div id='<%= #category.name %>' class='collapse'>\
<h4>Create a new item here:</h4>\
<div id='append<%= #category.id %>'></div>\
<%= link_to 'Home', root_url %>\ //does not work!
</div>");
}
It's just the link_to and other methods that seem to be causing a problem. All other erb tags <%= %> seem to work and render appropriately.
My goal is to render a form and a link in this newly rendered dropdown section, but since the root of the problem seems to be Rails methods in general, I added a link_to home for clarity.

Damnit, I figured it out. Forget to add 'j' to my rails helpers to convert them to JavaScript
<%= j link_to "Home", root_url %>

Related

How to show some stuff or a message beetween the main content in rails

I have a rails app where users can Sign Up/Sign In and post stories, follow other authors, what i want to achieve is how to put some content like "Authors to follow" in between of the main content while the user is scrolling (Like what twitter does with "Who to follow".
with react i have created a User_Follow_suggestion_container:
<%= react_component('FollowSuggestionsContainer') %>
It works fine, now i want to know, where to place it, so it can come randomly or after scrolling down to 20 or 30 posts.
Assuming your react component is inside a loop, you'd do something like this:
<%- #tweets.each_with_index do |tweet, index| %>
<%= tweet %>
<%- if index == 20 ( or 30 or even rand(20..30)) %>
<%= react_component('FollowSuggestionsContainer') %>
Sorry if the syntax is wrong. I haven't used ERB in years..
Edit: If you want it after scroll, you'd probably do something with JavaScript instead of Ruby/Rails.

rails render view onclick with javascript

I'm trying to create a view, where users can click on different buttons and render different content based on the buttons they click. I've tried getting this done with JS but can't really get it to work. I made a button in my view:
<div class="link">
<%= link_to "Greetings", "#" %>
</div>
<div id="show"></div>
then in job.js.erb:
$(function() {
$('.link').click(function() {
$('#show').append("<%=escape_javascript render(:partial => 'show' %>");
});
});
unfortunately render is not supported in assets, but I don't really know what the best way is to make this happen.
One way you can try is to let the button click go to a controller action, by AJAX, and then render the file with name <action_name>.js.erb. this file will then be able to call the render action.
I will expatiate more with the following:
Assuming the resource in question is Greetings and you have a dynamic_show action in the Greetings controller, for example, and you have a dynamic_show_greetings_path routing to this action.
From inside your view, you can have:
<div class="link">
<%= link_to "Greetings", dynamic_show_greetings_path, remote: true %>
</div>
<div id="show"></div>
and the Greetings#dynamic_show action will be like follow:
def dynamic_show
respond_to do |format|
format.js
end
end
then, in your view directory, you have a dynamic_show.js.erb file, which will contain the script to append the dynamic view as follow:
$('#show').html("<%=escape_javascript render(:partial => 'show') %>");
And that solves it for you!
Of course, to now make it dynamic, you have to then pass in params to the controller, and then render content based on the response gotten.
PS:
setting remote: true on the link ensures that the call will be an AJAX call.
controller actions by default renders the file with same name as the action name, therefore, dynamic_show responding to js will render dynamic_show.js.erb
Hope this throws a great light into it for you... ;)
It sounds like you need jQuery for this.
You can wrap the rendered partial in a parent div with a hide class. When the button is clicked toggle displaying the content.
http://api.jquery.com/show/
$('#your-button').click(function(e){
$('.hidden-div').toggleClass('hide');
});
There are two ways to do this.
Firstly, if you're wanting to load the JS on-page, you need to use what #anchalee suggested, and preload the content with some sort of "hide" class in the CSS:
#app/assets/javascripts/application.js
$(document).on("click", "a.hidden", function(e){
e.preventDefault();
el = $(this).attr("href");
$(el).toggle();
});
#app/views/controller/your_view.html.erb
<%= link_to "User", "#user", class: "hidden" %>
<div id="user" class="hidden">
Hello
</div>
This will take any divs with the id specified by the href attribute of the link, and then make it so that the div will hide or show depending on its current state.
--
Secondly, you have the off-page method (using ajax).
This is used to get data from the server, and will be where you'd load server-centric data such as what you're trying to do now.
Doing this is actually quite simple:
#app/controllers/your_controller.rb
class YourController < ApplicationController
layout: Proc.new{|c| !c.request.xhr? }
end
This will return any data you need without the layout:
#app/assets/javascripts/application.js
$(document).on("click", "#show", function(e){
e.preventDefault();
$.get($(this).attr("href"), function(data){
$("#show").html(data);
});
});
#app/views/your_controller/show.html.erb
<%= link_to "Show", [[url for page]], id: "show" %>

How to load partial into view when a link is clicked?

I have a list of user 'submissions' in my Rails app, and when a user submission is clicked, I would like the full submission to load into the view, without having to go to a new page.
Here's the code for the list of submissions:
<div id="submission-list-container">
<% current_user.submissions.each do |i| %>
<a href='#'>
<div id="post-container">
<%= i.title %>
</div>
</a>
<% end %>
</div>
The partial I have created, <%= render "show", :submission => i %>,, works fine, but I would like the full submission to be loaded into the view (index.html.erb), when that link above is clicked. Is there a good method for doing this? Should I just do something else like an AJAX call in JavaScript? I like these partials because it feels more clean and organized to seperate code.
My partial is pretty simple at the moment:
<%= submission.title %>
<%= dat_markdown(submission.content) %>
You can do this using a TitlePane in the Dojo Toolkit, and probably there's a similar widget with jQueryUI.
I can only speak to the Dojo Toolkit's version
You would do something like:
<div data-dojo-type="dijit/TitlePane" data-dojo-props="href: '/blah', title: '<%= submission.title %>', open: false">
You can include this in your application layout for lite usage of dojo, loaded from a CDN:
<script data-dojo-config="async: true, parseOnLoad: true"></script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js"></script>
The TitlePane is wired up so that when it is expanded, it will autoload the content that is provided to the href parameter.
While this isn't exactly a rails solution directly, it can be used as an alternative.
For a Rails Solution, you can simply use an AJAX call to a controller that renders the partial. You may even be able to hook it up using the
def blah
#submission = Submission.find(...)
respond_to do |format|
format.html # default render
format.js # js behavior
end
end
then a blah.html.erb
<%= render partial: 'submission/submission', object: #submission %>
with the partial
<div id='submission-<%= submission.id %>'>
<div id='submission-<%= submission.id %>-title'><%= link_to(submission.title, 'blah/blah', remote: true) %></div>
<div id='submission-<%= submission.id %>-content'></div>
</div>
and a blah.js.erb
$.get('/submission/content', function(data) { $('#submission-<%= #submission.id %>-content').html(data) } );
and an entry into the submissions_controller with route
def content
#submission = Submission.find(...)
render text: #submission.content
end
This probably isn't an exact solution, but hopefully it'll put you on the right path.

rendering a html.erb in rails with javascript

I create a page and some parts of it are layout files that are rendered. However I want to render one of these rendered part again with javascript code.
I want to render these part again
<div id="dialog" title="Bookmark Folders" style="resize: both;">
<%=render "layouts/filetree.html.erb"%>
</div>
It render function creates this:
<div id="accordion">
<% #user.folders.each do |f| %> <h3 id="<%= f.folder_name%>" class="folderBar"><b id="folderName"><%= f.folder_name%></b> created <%=distance_of_time_in_words(f.created_at, Time.now)%> before</h3>
<div class="<%= f.folder_name.delete(" ")%>">
<%if f.docs.empty?%>
<b>-No document currently!-</b>
<%else%>
<% f.docs.each do |r|%>
<%= r.title%><br/>
<b><%=r.url%></b><br />
<%= r.snippet%><hr/>
<%end%>
<%end%>
</div>
<%end%>
</div>
Because after some execution there are some changes over "folders", I want to render this part again to see the update.
You shouldn't attempt to render erb with javascript - it's not how it's done (not to mention you'd have to write yourself a erb parser and eventually call the server for data anyway).
If on the other hand, you're asking how to issue the render of some template using Javasript and then replace old content with new one then...
Watch this http://railscasts.com/episodes/205-unobtrusive-javascript,
read this Rails 3 and RJS to get the idea of how to trigger some content updates via javascript.
General idea is
Render the initial full page
Trigger ajax call (either after some time or by manual user request) to do a request to your rails application
Handle that request and respond to it with javascript script (the script content should contain all the functionality and content to replace what you want)
It's possible to share templates between the server and the client. One library that allows for this is called mustache.
But if this is the only case you need it I'd go with the RJS approach as well.
Instead of rendering I did it AJAX way and update it on the page. Thanks for the answers but I did not use any of these.

Removing :notice and <div> in Rails 3.1 app on page refresh

This might be an easy one for you guys, but I'm not sure the best way to achieve it.
Is there some type of .erb I can write that asks "If :notice is present, then render..."?
Here's more about the issue:
My controller specifies a :notice for both the create and update actions (pretty standard). When I load the pages, the notices do as I'd expect and show up. When I reload the page however, (not sure why someone would do this, but I did), the :notice goes away (great, that's what I want), but the containing <div> remains.
How do I go about ensuring that the encapsulating <div> is removed along with the :notice? I'm not sure what conditionals to specify in my view or maybe controller. The view looks something like this (btw, I'm using Twitter Bootstrap JS alerts).
View
<div class="alert-message success fade in" data-alert="alert">
<a class="close" href"#">×</a>
<p><%= notice %></p>
</div>
My controller is a single scaffolded model/resource with basic structure
What I did was:
<% if notice == "[:notice string]" %>
.
.
.
<% end %>
Not sure if this is the most efficient and "Rails-y" way to do it, but it worked for me.

Categories

Resources