Erick
Erick

Reputation: 6089

Handle many-to-many relationship in rails

I have a many-to-many relationship in a db I use with rails.

Say I have a schema that looks like this :

Cinemas
- cinema_id
- name

Movies
- movie_id
- name

Showtimes
- showtime_id - timestamp - movie_id - cinema_id

So basicaly : [Cinemas] 1 -- N [Showtimes] N -- 1 [Movies]

In one of my pages I have a cinema id and want to show the movies based on the cinema_id and group the showtimes per movie. I am not exactly sure on how to handle this properly. In .Net I would use a SelectMany linq operator and create a collection of movies but this does not seem to exists in ruby/rails.

One way to do this I think would be to do something like:

@showtimes = Showtime.where(:cinema_id, cinema_id)
@showtimes.each do |st|
  @movies.add(st.Movie) unless @movies.include? st.Movie
end

That would work ... but it seems ... ugly or it is just me ?

Upvotes: 0

Views: 108

Answers (2)

sockmonk
sockmonk

Reputation: 4255

Based on your schema, each showtime record will have exactly one movie and one cinema. You can easily get separate lists this way:

@showtimes = Showtime.where(:cinema_id, cinema_id).order(:showing_at)
@movies = @showtimes.map {|s| s.movie }

You might also want to look at the .group and .includes methods in ActiveRecord.

If you want to go straight to a list of movies showing at a certain cinema, you could also do this:

@movies = Movie.joins(:showtimes).where('showtimes.cinema_id = ?', cinema_id)

With that, you can loop over the movies and show each one's showtimes.

Upvotes: 1

Catfish
Catfish

Reputation: 19284

If you have your associations setup correctly in your model, you should be able to do something like this:

Controller:

@showtimes = Showtime.where(:cinema_id, cinema_id)

View:

<%= @showtimes.each do |showtime| %>
    <p><%= showtime.movie.name %></p>  
<% end %>

Upvotes: 1

Related Questions