DEV Community

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

Collapse
 
glaubersantana profile image
Glauber Santana • Edited

How about construct a class CoktailList that fetch and store the records from database as a hash in a instance variable, and delegate the [] method to that variable?

Just to add a example of implementation:

In cocktail_list.rb

class CocktailList
  def initialize(scope = :all)
    @list = Cocktail.send(scope).index_by(&:name)
  end

  # put any desirable hash method here
  delegate :size, :keys, :values, :each, :[], to: :@list
end

In controller:

@cocktail_list = CocktailList.new # or CocktailList.new(:for_sale)

In view:

<%= @cocktail_list["Margarita"] %>
Collapse
 
rpalo profile image
Ryan Palo

Ooh that would be clean too!