Displaying Key values of attr_accessible!

Hi malware :smile:

I think your data model may not be very good, in which case you should consider adding a Category model and do a one-to-many association. Then it will be much easier to do this kind of thing.

Anyways, if for some reason you don’t want to deal with that, you’ll need to roll up your sleeves and write some Ruby for that (I’m using plain classes, not ActiveRecord here):

class Show
  attr_accessor :title, :category

  def initialize(title:, category:)
    self.title    = title
    self.category = category
  end
end

class Category
  attr_accessor :title, :shows

  def initialize(title:, shows: [])
    self.title = title
    self.shows = shows
  end
end

def categorize_shows(shows)
  categories_cache = {}

  shows.each do |show|
    category_title = show.category
    category = categories_cache[category_title] ||= Category.new(title: category_title)
    category.shows << show
  end

  categories_cache.values
end

shows_from_database = [
  Show.new(title: 'A', category: 'Action'),
  Show.new(title: 'B', category: 'Action'),
  Show.new(title: 'C', category: 'Action'),
  Show.new(title: 'D', category: 'Romance'),
  Show.new(title: 'E', category: 'Romance')
]

puts 'Shows List'

shows_from_database.each do |show|
  p show
end

puts
puts 'Categories/Shows List'

categorized_shows = categorize_shows(shows_from_database)

categorized_shows.each do |category|
  puts category.title
  category.shows.each do |show|
    p show
  end
end

Outputs:

Shows List
#<Show:0x007fa188851728 @title="A", @category="Action">
#<Show:0x007fa1888511b0 @title="B", @category="Action">
#<Show:0x007fa188850328 @title="C", @category="Action">
#<Show:0x007fa188853140 @title="D", @category="Romance">
#<Show:0x007fa188a9fef8 @title="E", @category="Romance">

Categories/Shows List
Action
#<Show:0x007fa188851728 @title="A", @category="Action">
#<Show:0x007fa1888511b0 @title="B", @category="Action">
#<Show:0x007fa188850328 @title="C", @category="Action">
Romance
#<Show:0x007fa188853140 @title="D", @category="Romance">
#<Show:0x007fa188a9fef8 @title="E", @category="Romance">