Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how to exclude one item from an "each" method

I'm using the Enki blogging gem as a type of content management system. It allows you to create posts and pages. It automatically generates two pages (Home and Archives). I've also created two other example pages, Services and Products, and will create many more. Therefore, when I want to list all the pages on the home page, I do this

  <% page_links_for_navigation.each do |link| -%>
    <li><%= link_to(link.name, link.url) %></li>
  <% end -%>


Home
Archives
Services
Products

I may want to create more pages in the future, so it's better to loop over all the pages like this rather than hardcode the url for each page.

But how would I change that code if I wanted to exclude one of those pages (i.e. archives). Enki automatically generates that page and doesn't give me an option to delete it. Moreever, I don't want to delete Archives, because I want to use it where I post link to blog posts.

So, in short, how would I exclude one particular page from this code

  <% page_links_for_navigation.each do |link| -%>
    <li><%= link_to(link.name, link.url) %></li>
  <% end -%>

The url for Archives is localhost:3000/archives

like image 208
Leahcim Avatar asked Dec 04 '22 15:12

Leahcim


2 Answers

another way

<% page_links_for_navigation.each do |link| -%>
   <% next if link.name == 'Archives' %>
   <li><%= link_to(link.name, link.url) %></li>
<% end -%>
like image 56
abhas Avatar answered Dec 18 '22 08:12

abhas


  <% page_links_for_navigation.each do |link| -%>
    <%  if link.name != 'Archives' %>    
      <li><%= link_to(link.name, link.url) %></li>
    <% end %>
  <% end -%>

or use page_links_for_navigation.reject {|page| page.name == 'Archives'}.each

Edit:

to add more pages do !['Archives', 'Home'].include? link.name or just add the ones you want to include and remove !

read

http://www.humblelittlerubybook.com/

http://www.ruby-doc.org/docs/ProgrammingRuby/

like image 41
Sully Avatar answered Dec 18 '22 07:12

Sully