I’m currently making a tv show site in ruby, the attr_accessible of the movie are title ‘string’, duration ‘integer’, category ‘string’ img. I can currently get the title of the tv show, three of them to show in a carousel with this syntax;
<%= tv_show.title %>
But what I actually want to do is to be able to display the movies based on their categories, more accurately what’s in their attr_accessible - category, that is if I had several movies which were all drama for instance what would be the Syntax so that I could have all the tv shows with the attr_accesible - category of drama (category: “drama”) to be displayed on my page?
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