Skip to content

Instantly share code, notes, and snippets.

@jwoertink
Created November 8, 2013 22:25
Show Gist options
  • Select an option

  • Save jwoertink/7378673 to your computer and use it in GitHub Desktop.

Select an option

Save jwoertink/7378673 to your computer and use it in GitHub Desktop.
polymorphic association saving issue using mongoid
#Models
class Event
include Mongoid::Document
has_and_belongs_to_many :organizations, index: true
belongs_to :location, polymorphic: true, index: true
end
class Organization
include Mongoid::Document
has_and_belongs_to_many :events, index: true
end
class Venue
include Mongoid::Document
has_many :events, as: :location, autosave: true
end
#Code
org = Organization.first
ven = Venue.first
evt = org.events.create(location: ven)
org.events.count #=> 1
evt.location #=> #<Venue...
# How can I make this include the event?
ven.events.count #=> 0
@jwoertink
Copy link
Author

I could just do

ven.events << evt

But then I'd have to do that every time I created an event scoped from the organization.

@gevans
Copy link

gevans commented Nov 8, 2013

Are you including the :class_name option in your Event model for the location?

Edit: Disregard, I just noticed that's a polymorphic relationship.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment