0

so I have a Category model with a "has many" relationship to my Soup model.

Currently, I have my page rendering a list of Categories with the Soups within each below. The page output looks like this:

Ramen *Soup 1 *Soup 2 Other Soups *Soup 3 *Soup 4

I added the ability to click on the Category name to show/hide the Soups. But I'd like to have this functionality's scope limited to each Category. In other words, I'd like to have clicking "Ramen" show/hide Soup 1 and Soup 2 only. Right now, clicking any Category shows/hides all 4 Soups.

views> categories> index.html.erb

<ul id="folderList">
  <% @categories.each do |category| %>

  <li>
  <img src="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/folder-blue-128.png" alt="folder" width="10%">

  <%= link_to category.name, '#', id: 'show_catcontents' %> (<%= category.soups.count%>)

  <div id="catcontents">
    <ul>
    <%- category.soups.each do |soup| %>
      <li><%= soup.name %></li>
    <%- end %>
    </ul>
  </div>

  </li>
  <% end %>
</ul>

<script>    
  $(function() {
  $('a#show_catcontents').click(function(event){
    event.preventDefault();
    $('div#catcontents').toggle();
  });
});
</script>

Any and all help is appreciated

1 Answers1

1

An easy way to do this while not changing all that much is to add an id to each of your elements to further specify them in your embedded ruby, and then hide that specific element rather than the whole catcontents <div> in your Javascript hide function.

For example:

<div id="catcontents">
  <ul>
    <%- category.soups.each do |soup| %>
      <li id= <%= soup.name %> ><%= soup.name %></li>
    <%- end %>
  </ul>
</div>

And then of course just change your Javascript hide function to hide by the <li> id rather than the catcontents <div>.

Xander G.
  • 15
  • 7
  • Thanks for your help. Can you tell me how you'd refer to the li's ID in the JS function? I tried looking at this page for an answer but I'm confused on how to handle it in mine, as the ID is a variable http://stackoverflow.com/questions/18162197/rails-pass-data-to-javascript –  Nov 07 '16 at 21:32
  • Sure! As you're using jquery, you can take advantage of jquery selectors. To select an element by id, use `$("#id")`. For further reading on jquery selectors, you can check out the article [here](http://www.w3schools.com/jquery/jquery_selectors.asp) from w3schools – Xander G. Nov 08 '16 at 16:08
  • So I know how to use the jquery selector for a fixed ID, but in this case, I'm having trouble figuring out how to reference the <%= soup.name %> variable in my selector. How would I do that? Sorry for the noobness! –  Nov 08 '16 at 19:19
  • Ah don't worry about it; gotta start somewhere. I was thinking you could just pass the soup name as an argument to a generic hide-by-id function that takes the id parameter you give it and hides that element. Then you could just call that function given the soup name at any point in your control flow. – Xander G. Nov 08 '16 at 19:38