Basing a Model on a View
Basing a model on a view is actually straightforward. The syntax is the
same as it would be for a normal table. For the current_movie_showtimes table, our CurrentMovieShowtime class is defined like
this:
class CurrentMovieShowtime < ActiveRecord::Base belongs_to :movie belongs_to :theatre belongs_to :auditorium, :foreign_key => [:room, :theatre_id] end
We also define the inverse relationships in the related classes.
For example, in the Movie class, we
have associations to both the MovieShowtime class as well as the CurrentMovieShowtime class:
class Movie < ActiveRecord::Base has_many :movie_showtimes, :dependent => :destroy has_many :current_movie_showtimes end
The difference is that the relationship defined with the view cannot have a destroy dependency defined. You can only modify views by modifying the tables they depend on, so deleting from them would be meaningless (it would also cause an error).
The rest of the ActiveRecord magic still applies. You can access current showtimes directly through an association. For example:
cool_movie.current_movie_showtimes
You can also use all of the automatically defined ActiveRecord
accessor on the CurrentMovieShowtime
class itself as well:
CurrentMovieShowtime.find_all_by_theatre_id(@theatre.id)
Our original example of finding “current movies in my area” is now much simpler as well:
CurrentMovieShowtime.find(:all, :conditions => [' miles_between_lat_long( current_movie_showtimes.lat, current_movie_showtimes.long, ?, ? ) < ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access