Search code examples
ioscore-datarubymotion

Relating one object to several others


I am having an issue implementing the following use case:

A Foo has a to-one relationship to a Bar, via a relationship named myBar. More than one Foo can have the same Bar, however.

I am coming from a web application background, where I would give Foo a bar_id, and have the myBar relationship method query for all Bars with that bar_id. I am aware that Core Data isn't an ORM, but I was hoping that something similar may be possible.

The problem I am experiencing is that setting the same Bar instance to several Foos causes the previous relationships to revert to nil.

Do I have no choice but to implement a many-to-many relationship? I really wanted to just call the myBar method and have it return the Bar instance, not a set of what will only ever be 1 Bar.

I am implementing this project in RubyMotion and include an example of my problem below. Objective-C devs shouldn't have a problem following, but this question is more one of principle than specific code I have written.

# assume `b` is some instance of Bar

f1 = Foo.alloc.init
f1.bar = b
# calling f1.bar getter now returns the `b` instance of Bar

f2 = Foo.alloc.init
f2.bar = b

# f2.bar getter returns the Bar instance, but *f1.bar does not* - it is now nil.

Solution

  • Found the problem:

    The FooBar relationship was correctly set as to-one, but, the inverse (BarFoo) wasn't set as to-many.