Ruby on Rails Join table relationship
-
03-07-2019 - |
Question
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
Solution
@showing_list is an array.
@showing_list.collect(&:movie).uniq
OTHER TIPS
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
Try:
named_scope :find_sorted_showings, lambda { |order|
{ :order => order }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow