Storing Movie Sequels and Prequels - ruby-on-rails-3

Given that I have a model that stores movies, what would be the best way to specify relationships such as movie sequels and prequels?
I'd like to access these relationships using simple accessors such as movie.sequels (which would return an ordered list of movies that are sequels to movie) and move.prequels.
I've considered using a has_many :through relationship with a secondary model but how would I maintain movie sequence?
Or could there be a better methodology entirely?

An easy way could be using an ActiveRecord plugin like acts_as_list which allows you to define ordering between different items. You'd need to add a field to use as a scope, such as saga, so the order is defined within movies which belong to the same saga.
https://github.com/swanandp/acts_as_list
The plugin provides handy methods lower_items and higher_items which would work like the sequels and prequels methods you are looking for,

Related

Can two compositions own the same object?

I'm trying to make a class diagram for an Online Auction System and I'm having this problem. Bids belong to both the Auction and the Buyer (Correct me if i'm wrong). So can I say that User is composed of bid AND auction is composed of Bid or is this against the rules of UML? I'm confused
In general
The term composition is ambiguous and this explains your confusion:
In OOP, object composition means to use an object in another one.
In UML, composition is a special kind of association that represents a part-whole relationship, with an exclusive ownership of the parts by the whole.
So in the UML sense, it is not possible to have an object that is part of two different compositions, because the ownership would no longer be exclusive. But you could use the object in several aggregations, which are a whole-part relations allowing a shared ownership.
In the OOP sense, there is no problem of having the same object used in (or using) several compositions. The object composition corresponds to a navigable UML association.
In your practical case
The situation is straight forward: A Bid has one Buyer, a Buyer may have several Bids, and an Auction has several Bids. You can model this with simple associations:
You could alternatively use an aggregation here, since one could argue that there is a whole-part relation between an Auction and the corresponding Bids (personally, I wouldn't see it like this):
You should however not see an aggregation on the other side, because there is no real whole-part relation between a Buyer and a Bid: a Buyer is not "made of several Bids".
Additional remarks
You could use also an association class here. But it's not required. And the semantic would be different: it would mean that there is a Bid association between a Buyer and an Auction:
Technically speaking, you'd still have three classes.
But the focus is different: the Bid is accessory to the Buyer and the Auction and cannot exist on its own (e.g. if the buyer disappears)
Have you learned about association classes in UML? They represent an object that is created from the relationship between two other classes, exactly what you are trying to map. There are plenty of contents detailing Association Classes (e.g. Correct use of an association class)
That way you shouldn't get confused reading the diagrams (which you were doing correctly btw), it would be clear to you that exists the entity Bid, which exists only associated to both Buyer and Auction.

DDD how to save relationship between entities?

I am new to DDD world, I want to apply it to our DDD application with ADO.NET. There are entities, aggregate root, value object in DDD. I have two entities, such as a blog post which maybe can belong to several categories. Actually I think the blog post and the category all should be aggregate root. The blog post and the category all have a repository, PostRepository and CategoryRepository, but now i am confused about how to implement the persistence of the 1:many relationship between post and category entities.
In DAO pattern, there is an DAO corresponding to a table, we can persist the relationship in the DAO class. But in DDD, there are concept of Unit of work, it can ensure the aggregate root work correctly, like this, there should be some repositories about the entities of the aggregate root. but for the relationship I don't think it should have a repository, it is not a entity here.
Is there a best practice to solve these scenarios? or should I add two procedure(add post, add category) and call them when I save the post?
You should have a single repository per aggregate root.
If you think about a structure of objects, like your Posts, then the aggregate would be the Post with a Category. The Post would be the aggregate root. If an entity is just on it's own, you could think of it as an aggregate root in itself (just an aggregate of one object). So your rules for creating repositories, is one for each aggregate root (or single entities of one object).
If you make Category part of the Post aggregate, then you must never access or modify Categories directly. If a Category needs changing, it is done through the Post object. If this doesn't sound like your domain model and you're thinking "but I want to manage my Categories separately", then there's a good chance that Category doesn't belong to the Post aggregate. If not, you probably want to model the Category as it's own entity and reference it by id (not object reference) from the Post entity.
How you then go on to model Categories depends on your own Domain. This happens a lot with DDD. But it's all good. It just means that the way you model your domain is 100% dependent on how your particular domain works.

How can we have an Association that is not an Aggregation?

Aggregation is defined as a special case of association. However, any association that is not implemented as a field (like having a relationship through method parameters) are being described as "use" relationship.
So, is it possible to have an association that is not aggregation or composition? If yes, I need a code example for such a case, please.
In fact, I'd say that most cases of associations in models are neither aggregations nor compositions (both are forms of part-whole relationship types). For instance, the association between the classes Publisherand Book for assigning the books published by a publisher to this publisher is neither an aggregation nor a composition because the books published by a publisher are not parts or components of this publisher.
For implementing this bidirectional association, we use the two mutually inverse reference properties Publisher::publishedBooks and Book::publisher, as shown in the following class rectangles:
Notice that the multi-valued reference property Publisher::publishedBooks is normally implemented by a list-valued property in Java.
I have explained how to use associations and reference properties in design models in my tutorial Managing Unidirectional Associations in a JavaScript Frontend Web App.
Shared aggregation (empty diamond) is not defined strictly in the UML standard. So, it is not easy to find a situation, where you can not use it.
But it is explicitely forbidden to use it for both sides of association. So, if you have relation many to many, you have to show it on class diagram as many to many association with none aggregation. Of course, you can show it as TWO shared association, but it is not our target, is it? :-)
As for code, if people visit many courses and courses are visited by many people, make a list "courses" for Person class and a list "visitors" for Course class.
Of course, on the other side, you always can use none instead of shared for any shared association, it is at your wish and up to rules of your place of work. But I don't know these rules, sorry :-). But surely, nobody will make you to use aggregation for 1 to 1 association.

How does one architect an entity in Core Data with a generic relationship?

Say you need to architect an app with an entity that can be associated with multiple other kinds of entities. For example, you have a Picture entity that can be associated with a Meal entity, a Person entity, a Boardroom entity, a Furniture entity, etc. I can think of a number of different ways to address this problem, but -- perhaps because I'm new to Core Data -- I'm not comfortable with any of them.
The most obvious approach that comes to mind is simply creating a relationship between Picture and each entity that supports associated pictures, but this seems sloppy since pictures will have multiple "null pointers."
Another possibility is creating a superentity -- Pictureable -- or something. Every entity that supports associated pictures would be a subentity of Pictureable, and Picture itself would have a one-to-one with Pictureable. I find this approach troubling because it can't be used more than once in the context of a project (since Core Data doesn't support multiple inheritance) AND the way Core Data seems to create one table for any given root entity -- assuming a SQLite backing -- has me afeard of grouping a whole bunch of disparate subentities under the umbrella of a common superentity (I realize that thinking along these lines may smack of premature optimization, so let me know if I'm being a ninny).
A third approach is to create a composite key for Picture that consists of a "type" and a "UID." Assuming every entity in my data model has a UID, I can use this key to derive an associated managed object from a Picture instance and vice versa. This approach worries me because it sounds like it might get slow when fetching en masse; it also doesn't feel native enough to me.
A fourth approach -- the one I'm leaning towards for the app I'm working on -- is creating subentities for both Picture and X (where X is either Meal, Person, Boardroom, etc.) and creating a one-to-one between both of those subentities. While this approach seems like the lesser of all evils, it still seems abstruse to my untrained eye, so I wonder if there's a better way.
Edit 1: In the last paragraph, I meant to say I'm leaning towards creating subentities just for Picture, not both Picture and X.
I think the best variations on this theme are (not necessarily in order):
Use separate entities for the pictures associated with Meal, Person, Boardroom, etc. Those entities might all have the same attributes, and they might in fact all be implemented using the same class. There's nothing wrong with that, and it makes it simple to have a bidirectional relationship between each kind of entity and the entity that stores its picture.
Make the picture an attribute of each of the entity types rather than a separate entity. This isn't a great plan with respect to efficiency if you're storing the actual picture data in the database, but it'd be fine if you store the image as a separate file and store the path to that file in an attribute. If the images or the number of records is small, it may not really be a problem even if you do store the image data in the database.
Use a single entity for all the pictures but omit the inverse relationship back to the associated entity. There's a helpful SO question that considers this, and the accepted answer links to the even more helpful Unidirectional Relationships section of the docs. This can be a nice solution to your problem if you don't need the picture->owner relationship, but you should understand the possible risk before you go down that road.
Give your picture entity separate relationships for each possible kind of owner, as you described in the first option you listed. If you'll need to be able to access all the pictures as a group and you need a relationship from the picture back to its owner, and if the number of possible owner entities is relatively small, this might be your best option even if it seems sloppy to have empty attributes.
As you noticed, when you use inheritance with your entities, all the sub-entities end up together in one big table. So, your fourth option (using sub-entities for each kind of picture) is similar under the hood to your first option.
Thinking more about this question, I'm inclined toward using entity inheritance to create subentities for the pictures associated with each type of owner entity. The Picture entity would store just the data that's associated with any picture. Each subentity, like MealPicture and PersonPicture, would add a relationship to it's own particular sort of owner. This way, you get bidirectional Meal<->MealPicture and Person<->PersonPicture relationships, and because each subentity inherits all the common Picture stuff you avoid the DRY violation that was bugging you. In short, you get most of the best parts of options 1 and 3 above. Under the hood, Core Data manages the pictures as in option 4 above, but in use each of the picture subentities only exposes a single relationship.
Just to expand a bit on Caleb's excellent summation...
I think it's important not to over emphasize the similarities between entities and classes. Both are abstractions that help define concrete objects but entities are very "lightweight" compared to classes. For one thing, entities don't have behaviors but just properties. For another, they exist purely to provide other concrete objects e.g. managed object context and persistent stores, a description of the data model so those concrete objects can piece everything together.
In fact, under the hood, there is no NSEntity class, there is only an NSEnitity***Description*** class. Entities are really just descriptions of how the objects in an object graph will fit together. As such, you really don't get all the overhead an inefficiency of multiplying classes when you multiply entities e.g. having a bunch of largely duplicate entities doesn't slow down the app, use more memory, interfere with method chains etc.
So, don't be afraid to use multiple seemingly redundant entities when that is the simplest solution. In Core Data, that is often the most elegant solution.
I am struggling with esactly this dilemma right now. I have many different entities in my model that can be "quantified". Say I have Apple, Pear, Farmer for all of those Entities, I need a AppleStack, PearStack, FarmerGroup, which are all just object+number. I need a generic approach to this because I want to support it in a model editor I am writing, so I decided I will define a ObjectValue abstract entity with attributes object, value. Then I will create child entities of ObjectValue and will subclass them and declare a valueEntity constant. this way I define it only once and I can write generic code that, for example, returns the possible values of the object relationship. Moreover if I need special attributes (and I actually do for a few of those) I can still add them in the child entities.

How to bind an NSTableView to multiple core data entity types

I'm writing an application to help diabetics manage their condition. Information that is tracked includes blood sugar results, nutrition, exercise, and medication information.
In similar applications these entries are all presented in a single table view even though each type of entry has different fields. This data is manually tracked by many diabetics in a logbook, and I'm looking to keep that paradigm.
Each entry has some common information (timestamp, category, and notes) as well as information specific to each entry type. For instance, meal entries would have detailed nutrition information (carb counts, fiber, fat, etc), medication entries would indicate which medication and dosage, etc.
I've considered two different approaches but I'm getting stuck at both a conceptual level and a technical level when attempting to implement either. The first approach was to create an abstract entity to contain all the common fields and then create entities for each log entry type (meals, meds, bg, etc.) that are parented to the abstract entity. I had this all modeled out but couldn't quite figure out how to bind these items to an array controller to have them show up in a single table view.
The second approach is to have one entity that contains the common fields, and then model the specific entry types as separate entities that have a relationship back to the common record (sort of like a decorator pattern). This was somewhat easier to build the UI for (at least for the common field entity), but I come to the same problem when wanting to bind the specific data entities.
Of course the easiest approach is to just throw all the fields from each different entry type into one entity but that goes against all my sensibilities. And it seems I would still run into a similar problem when I go to bind things to the table view.
My end goal is to provide an interface to the user that shows each entry in chronological order in a unified interface instead of having to keep a separate list of each entry type. I'm fine with adding code where needed, but I'd like to use the bindings as much as possible.
Thanks in advance for any advice.
Don't get bogged down with entity inheritance. You shouldn't use it save duplicate attributes like you would with classes. It's major use is allow different entities to be in the same relationship. Also, entity inheritance and class inheritance don't have to overlap. You can have a class inheritance hierarchy without an entity inheritance hierarchy.
I'm not sure I understand exactly what you really need but here's some generic advice: You shouldn't create your data model based on the needs of the UI. The data model is really a simulation of the real-world objects, events or conditions that your app deals with. You should create your data model first and foremost to accurately simulate the data. Ideally, you should create a data model that could be used with any UI e.g. command-line, GUI, web page etc.
Once your model is accurately setup, then whipping up the UI is usually easy.