stellard
stellard

Reputation: 5314

Ruby on Rails Join table relationship

I am trying to use my join table "showing" to get a list of movies

I was trying to use this code but it does not work.


@showing_list = Showing.find_sorted_showings("time")

@movie_list = @showing_list.movies <-- NoMethodError 

Here is my Showing class


class Showing < ActiveRecord::Base
belongs_to :movie


def self.find_sorted_showings(order)
    find(:all, :order => order)
end
end

How can I change my showing class to get the move_list from the showing_list without doing it manually?

Thank you

Upvotes: 0

Views: 3920

Answers (3)

Christopher Hazlett
Christopher Hazlett

Reputation: 326

Use the eager loading capability:

   def self.find_sorted_showings(order)
    find(:all, :order => order, :include => :movie)
   end

The resulting data set will now include the movie along with the show times accessible via:

@showing.each do |show_time|
  show_time.movie.title
end

Of course, this poses grouping issues if you're looking to create a more readable list. but you can do some pretty fancy stuff with the group_by method, like:

find(:all, :order => order, :include => :movie).group_by {|s| s.show_time}

Hope that helps.

-Chris

Upvotes: 2

Sophie Alpert
Sophie Alpert

Reputation: 143134

Try:

named_scope :find_sorted_showings, lambda { |order|
  { :order => order }
}

Upvotes: 1

Allyn
Allyn

Reputation: 20441

@showing_list is an array.

@showing_list.collect(&:movie).uniq

Upvotes: 3

Related Questions