Underscore Template with Ruby Backend not working - ruby-on-rails

I am using the underscore template to create a template for making bootstrap dropdown menus. The code worked fine on my own computer, but now I'm adding it to a ruby on rails backend server. Now the code no longer works. I was told the code in between the <% %> is interpreted as ruby code instead of javascript. I don't know ruby at all, but someone showed me how to write a for loop.
<!-- Dropdown Menu-->
<script type="text/template" id="dropdown">
<div class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">
<span> <%= name %> </span>
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<% array_of_items.each do |obj| %>
<li> <a> <%= obj %> </a> </li>
<% end %>
</ul>
</div>
</script>
The error I get is "Undefined variable array_of_items" Of course it's not defined, I define it later on
this.$el.append(this.makeDropdown({
name: this.name,
array_of_items: [1,2,3,4]
}));
The underscore template works like this for Javascript, but for Ruby it will not allow me to have an undefined variable in a template for some reason, What can I do?

So the problem I think is here:
<% array_of_items.each do |obj| %>
Rails is interpreting this as ERB, and as there's no variable declared in Ruby, you're getting the error. Try adding your JS code into the asset pipeline perhaps?

Javascript's and ruby's variable are in quite different 'scopes';
here <% array_of_items %> should be defined as a template local variable:
<% array_of_items = [1,2] %>
<%= array_of_items %>
<script>
document.body.innerHTML += array_of_items;
array_of_items = ['j', 's'];
document.body.innerHTML += array_of_items;
// var from js + var from ruby
document.body.innerHTML += array_of_items + <% array_of_items %>; // #=> should be smth like `js12`
</script>

Related

How ignore empty response in ruby view loop

as i'm new to ruby and rails in general i would have a short question cause i'm stuck at a minor issue.
I'm calling a content API from my controller and looping thru the response in the view directly. The main problem is: If one of the objects, has an empty value which i'm calling..it breaks the view.
Question would be how can i scip the elements which are emtpy...in example if post["heroimage"]["url"] is empty?
Example view:
<div class="gallery">
<% #blog.each do |post| %>
<a target="_blank" href="blog/<%= post["id"] %>">
<img src="<%= #host + post["heroimage"]["url"]%>" alt="" width="600" height="400">
</a>
<div class="desc"><%= post['description'] %></div>
<% end %>
</div>
There is nothing Rails or Rails views specific about your question. What you're trying to do is skip elements in an each loop in Ruby, and the answer is, next
somethings.each do |thing|
next if thing.nil?
# .. does not get called if thing is nil
end
From what I understand from the question and your comments you can use,
post.dig("heroimage", "url")
here is the link to dig method documentation. If you want to skip the image in case of empty url you can do something like this
<div class="gallery">
<% #blog.each do |post| %>
<a target="_blank" href="blog/<%= post["id"] %>">
<% if post.dig("heroimage", "url") %>
<img src="<%= #host + post["heroimage"]["url"]%>" alt="" width="600" height="400">
<% end %>
</a>
<div class="desc"><%= post['description'] %></div>
<% end %>
</div>
This will still show the title even if the image URL is empty.

Rails is not rendering my HTML data attributes (RefineryCMS)

I have the following view refinery/portfolio/items/_item.html.erb from RefineryCMS and for some reason my data-attributes are not being rendered into the DOM.
From my understanding it seems that RefineryCMS is potentially removing them?
Rails 4.2.6 and latest master branch of RefineryCMS
Here is my ERB template:
<li class="col-md-3 col-xs-6 thumb">
<a class="thumbnail" data-toggle="tab" data-target="#tab_<%= dom_id(item) %>">
<%= image_tag(item.image.url, {:title => item.title}) %>
</a>
</li>
Also tried:
<li class="col-md-3 col-xs-6 thumb">
<%= link_to "", class: "thumbnail", data: { toggle: "tab", target: "#tab_#{dom_id(item)}" } do %>
<%= image_tag(item.image.url, {:title => item.title}) %>
<% end %>
</li>
It then renders HTML as:
<a class="thumbnail">
<img title="title" src="/img.png" alt="alt_title">
</a>
After visiting the RefineryCMS Gitter chat, I was able to get the assistance I needed. The problem was recently in RefineryCMS 3 release they started sanitizing HTML data attributes.
So I added the following configurations to my config/initializers/refinery/pages.rb:
config.layout_template_whitelist = ["application"]
config.add_whitelist_elements = %w[ source track ]
config.add_whitelist_attributes = %w[ kind srclang placeholder controls data-target data-toggle ]

Ruby: Changing an array of items into links in an ERB

I have an array of strings that I want to interpolate into links within an erb file.
How would I approach this syntactically?
Currently, I have the following
<% names.each do |name| %>
<b>
<%=name%>
</b>
<%end%>
<% navigation=["home","about us","store","contact","blog"] %>
<%navigation.each do |navitem| %>
<ul>
<li>
<a href= <%=/#{navitem}/%>".html">
<%=navitem%>
</a>
</li>
</ul>
<%end%>
Change
<a href= <%=/#{navitem}/%>".html">
to
<a href="<%= navitem %>.html">

Reading erb form fields, Rails4

Question about Rails4, I trying to retrieve the "Find Stuff" variable, in the erb form. This
is a search field, using zurb foundation - so the extra styling annotations floating around.
I don't have a model as this is just a form for reading the search input field - which is
in the tag, with placeholder as "Find Stuff".
To use normal Rails4 terminology, I would
like to pass the value of the "Find Stuff" field to the salutation controller, and I tried
many ways, but was unsuccessful, when I used render params[:post].inpect, it shows nil -the
variables that I pass to the controller, on clicking on the "Search" link_to, link. I tried adding an id field to the tag, and that too showed nil on render params[:post].inspect.
Any help, thanks in anticipation.
hello.html.erb form below.
<html>
<body>
<nav class="top-bar" data-topbar>
<ul class="title-area">
<li class="name">
<h1>Hello World!</h1>
</li>
<li class="toggle-topbar menu-icon"><span>Menu</span>
</li>
</ul>
<ul class="right">
<li class="has-form">
<div class="row collapse">
<div class="large-8 small-9 columns">
<input type="text" placeholder="Find Stuff" >
</div>
<div class="large-4 small-3 columns">
<%= link_to "", :controller =>
'salutation', :action =>'hello',
:class=>"alert button expand" %>
</div>
</div>
</li>
</ul>
</section>
</nav>
</body>
</html>
Controller follows
Salutation Controller follows
class SalutationController < ApplicationController
def new
#test = ''
end
def hello
#message = 'Hello World!'
#test = params[:Find_Stuff]
end
end
Wrap your search box in a form element, give your input a name and away you go. You can use the rails form helpers as well - see http://guides.rubyonrails.org/form_helpers.html which has a nice intro to creating a search form
<div class="row collapse">
<%= form_tag("/salutation/hello", method: "post") do %>
<div class="large-8 small-9 columns">
<%= text_field_tag(:find_stuff) %>
</div>
<div class="large-4 small-3 columns">
<%= submit_tag("Search") %>
</div>
<% end %>
</div>
Further to #slapthelownote's answer, the reason you're getting an error is because you're not passing any params to your controller
We've got something like what you want working at http://firststopcosmeticshop.co.uk (top search box) -- using a form_tag
If you want to see live code, I'll be happy to post!
Params
Using a form allows you to set various variables & then submit them to the controller as you've set them. I'd recommend using the form in the other answer, but to understand how it works, you need to read up on the Rails forms tutorial
Basically, the params hash is populated in the middleware of Rails -- from any data sent by HTTP to your backend
With links, you can only send GET params (domain.com/route&params=value), whilst with HTML forms, you can set POST params which are passed through the browser (not the URL)

Rails object deleted in development, but apparently not in production. Why?

I have a bunch of College objects. I print them all out here: http://www.collegeanswerz.com/colleges. (excluding the alphabetical tab. for that I hand coded the HTML)
Take the Rank tab as an example. (The Size and Table tabs are analogous to this code.)
<div class="tab-content">
<div id="national_universities2" class="tab-pane active">
<h3>National Universities</h3>
<nav class="list">
<ol>
<% #national_university_rank.each do |school| %>
<li value="<%= school.us_news_ranking %>"><%= link_to school.name, '/'+school.url %></li>
<% end %>
</ol>
</nav>
<br />
<p class="usnews">Ranks according to <%= link_to "US News", "http://colleges.usnews.rankingsandreviews.com/best-colleges" %>.</p>
</div>
<div id="liberal_arts_colleges2" class="tab-pane">
<h3>Liberal Arts Colleges</h3>
<nav class="list">
<ol>
<% #liberal_arts_college_rank.each do |school| %>
<li value="<%= school.us_news_ranking %>"><%= link_to school.name, '/'+school.url %></li>
<% end %>
</ol>
</nav>
<br />
<p class="usnews">Ranks according to <%= link_to "US News", "http://colleges.usnews.rankingsandreviews.com/best-colleges" %>.</p>
</div>
</div>
There are a couple of colleges that I deleted using rails console. They aren't showing up in the development version of this web page, but they are in the production version. Why is this?
I assume you've figured this out already, but it's probably because you deleted them in development which means the development database which is not the same as the production database (in a typical rails setup). Each environment has its own database. If they look the same it's because you (or a previous developer) cloned databases from one environment to another for testing or other purposes.
If you want to remove them from production, you need to get on that machine (wherever it's hosted) and run the same steps you ran in development to remove those records.

Resources