Displaying Key values of attr_accessible!

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?

Help anyone?

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

Thanks a bunch, man! This was very helpful, sorry for the late response!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.