Fajar A b wrote:
This is what I ended up doing:
class Photo < ActiveRecord::Base
belongs_to :user
belongs_to :destination
belongs_to :content, :polymorphic => true
class Destination < ActiveRecord::Base
has_many :photos
class Trip < ActiveRecord::Base
belongs_to :user
belongs_to :destination
This way I can do destination.photos and get all photos for that
destination even though the content is Trip or anything else. What do
you guys think?
Andrew,
Destination usually a city and hotel must belongs to a destination.
I must be missing something here - where is “has_many :photos, :as =>
:content” used?
Looks like your on the right track, but let me have a crack (without
fully understanding your requirements).
We have a few moving parts - users, photos, destinations, and trips. A
user wants to plan their holiday by building up a series of destinations
into a trip. They may want to look at photos of their destinations to
choose good looking hotels to stay at. Users can also upload photos of
destinations they have visited for others to look at. Given this, the
models would look something like:
class User < ActiveRecord::Base
has_many :trips
has_many :photos
has_many :destinations, :through => :trips
end
class Trip < ActiveRecord::Base
belongs_to :user
has_many :destinations
has_many :photos, :through => :destinations # Is this useful?
end
class Destination::ActiveRecord::Base
belongs_to :trip
has_many :photos, :as => photographable
has_many :users, :through => trips # So we can look up users who have
been here.
end
class Photo < ActiveRecord::Base
belongs_to :user
belongs_to :destination
has_many :trips, :through => :destinations # Not sure if this works
belongs_to :photographable, :polymorphic => true
end
Now you can call the following in your controllers/views:
user.trips # List all the trips a user has created
user.photos # List all the photos a user has uploaded
trip.destinations # List the destinations associated with a trip
destination.photos # List all the photos for a given destination
trip.photos # Grab all the photos attached to all the
destinations in this trip
etc.