loading...

re: What's the best way to render specific items from a Rails collection? VIEW POST

FULL DISCUSSION
 

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"] %>
 

Ooh that would be clean too!

code of conduct - report abuse