What's the best way to render specific items from a Rails collection?

Ryan Palo - Jun 23 '20 - - Dev Community

Hi! I've got a small Rails app where I'm going to have a small number (<200) of rows in a database. When I display them, order is going to important to me (making a menu, so I'd like to be able to control which item goes where).

I imagine that querying the database for each individual item as I come to it is not efficient. So I believe what I probably want to do is get all of them and pass them to the view and have the view decide where they should go.

I'd like to be able to do something like this:

<h2>Summer Drinks</h2>

<%= @cocktails["Margarita"] %>

<!-- Or even better yet: -->

<%= cocktail "Margarita" %>
Enter fullscreen mode Exit fullscreen mode

I know that I could have the controller map over the records and store them in a hash by name, pass that hash to the view, and subsequently write a helper function to provide the syntactical sugar. But, is there an easier, Railsier way to do it? It feels like there should be, but my searching hasn't turned up anything.

If it helps, I've got a unique index on the Name column of the Cocktails table.

Additionally, I don't plan to add/update cocktails (think 1-2 database changes/week). I could lean pretty heavily on caching/precompiling if that's a factor in the solution.

Thank you!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player