Reputation: 14046
Consider the following:
class Picture
include Mongoid::Document
field :data, :type => String
end
class Cat
include Mongoid::Document
has_one :picture, :autosave => true
field :name, :type => String
end
class Dog
include Mongoid::Document
has_one :picture, :autosave => true
field :name, :type => String
end
Now, is it possible to do the following:
dog = Dog.new
dog.picture = Picture.new
dog.save!
Without having to edit the Picture class to the following:
class Picture
include Mongoid::Document
belongs_to :cat
belongs_to :dog
field :data, :type => String
end
I don't need pictures to know about it's Dog
or Cat
. Is this possible?
Upvotes: 0
Views: 192
Reputation: 18203
I believe you could do this if you put the belongs_to :picture
in your dog and cat classes. The side of the relation that has belongs_to
is the side that will store the foreign key. That would put a picture_id
field in each of Dog
and Cat
, instead of having to store a whatever_id
for each type of think you want to link on your Picture
class.
Upvotes: 1
Reputation: 83680
No it is not. You need to have cat_id
or dog_id
or some polymorphic obj_id
for all of them to store information about belonging of this picture.
Or how do you know wich Picture belongs to current Dog or Cat?
Upvotes: 0