Rails - Indexing records based on their category

201 views Asked by At

My project is setup where each movie has many genres and each genre has many movies. So for instance a movie can have one or more genres of such categories: Action, Comedy, Drama. What I'd like to do is create views for each genre that list the movies that belong to them, similar to how the default index action is setup:

class Movie < ActiveRecord::Base
    attr_accessor :name
    has_many :genreships
    has_many :genres, through: :genreships

    extend FriendlyId
    friendly_id :name, use: :slugged
end

class Genreship < ActiveRecord::Base
    belongs_to :movie
    belongs_to :genre
end

class Genre < ActiveRecord::Base
    attr_accessor :name
    has_many :genreships
    has_many :movies, through: :genreships

    extend FriendlyId
    friendly_id :name, use: :slugged
end

Movies Controller

def index
  @movies = Movie.all
end

Movies Index View

<% @movies.each do |movie| %>
  ...
<% end %>

With each genre-based url looking something like this: localhost:3000/comedy

I realize that creating an index action for each and every genre wouldn't scale well so I'm wondering what would be the best solution to dynamically create these pages. I've done some research regarding to the topic but most of them have been geared towards creating nested routes where as I'm leaning more towards the Action View.

1

There are 1 answers

12
BroiSatse On BEST ANSWER

Firstly, you need routes:

get '/:genre', to: 'movies#genre_movies'

Then your action will read:

def genre_movies
  @movies = Genre.find_by(name: params[:genre]).movies
  render 'index'
end