简体   繁体   中英

Ruby on rails - Changing hyperlinks to table columns

I've made a list with hyper links to columns in a table called "Categories", there are 5 categories and the first set of code below makes hyperlinks to all 5.

I want to make a dropdown menu, but only show two of the categories, instead of all 5. Currently, i'm just using a href to the url, but is there some other way I can link to two columns in the "Categories" table?

Links:

<ul>
    <% Category.all.each do |category| %>
    <li><%= link_to category.name, items_path(category: category.name) %></li>
    <% end %>
</ul>

Dropdown Menu:

<div class="container">
  <div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Canon
    <span class="caret"></span></button>
    <ul class="dropdown-menu">
        <li><a href="http://localhost:3000/items?category=Canon+Camera">Canon Cameras</a></li>
        <li><a href="http://localhost:3000/items?category=Canon+Lens">Canon Lenses</a></li>
    </ul>
  </div>
</div>

Use take() or limit() methods to limit how many items you want to get:

<ul>
    <% Category.take(2).each do |category| %>
    <li><%= link_to category.name, items_path(category: category.name) %></li>
    <% end %>
</ul>

With respect to your question "can link to two columns in the "Categories" table?" - Please find my comment as:

SQL Approach:

SELECT CONCAT('', "name", "title") AS "name" FROM categories;

Rails Approach: <%= link_to "#{category.name} #{category.title}", items_path(category: category.name) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM