DEV Community

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

Collapse
 
ben profile image
Ben Halpern • Edited

What about...

In the controller:

@cocktails = Cocktail.for_sale.to_a # for_sale scope or whatever, solidified as Array.

Helper:

def cocktail(cocktails, name)
  cocktails.select { |c| c.name == name }.first
end

This way you select from the array each time.

If you really want to make the query maximally efficient, you could use pluck which would return an array of arrays containing the values you need. So...

In the controller:

@cocktails = Cocktail.for_sale.pluck(:name, :description, :price) # @cocktails[0] would look like ["margarita", "Good drink", 9] or whatever.

Helper:

def cocktail(cocktails, name)
  cocktails.select { |c| c[0] == name }.first
end

I might be offbase in how I'm thinking about this, but at least it might help you look up some of these methods for use now and/or future.

Collapse
 
rpalo profile image
Ryan Palo

Ok, that makes sense. Scopes and pluck are definitely very useful features to know about. Is there any specific reason that you're sticking to using an array rather than converting to a hash? Or just because arrays are simpler to get to?