OrdersPerson.create( order: order4, person: person) OrdersGroup.create( order: order4, group: group) Order4 = Order.create( order_ref: "Or004") And it does not enforce uniqueness across the two owners (e.g one order could be incorrectly connected to both a person and a group).
In this approach, we don’t create foreign keys on either of the tables that we want to relate together.
Activerecord validation check without populating errors update#
Rails and ActiveRecord help us out on the surface, but anyone with direct access to the database can create or update objects that reference null objects. This means we lose the protection that foreign keys offer. We use the resource_type and resource_id columns in place of a foreign key. Unfortunately, polymorphic classes can’t have foreign keys. If someone tries to create an object with a foreign key that references a null object, they will get an error. Foreign keys also prevent referential errors by requiring that the object referenced in the foreign table does, in fact, exist. They have more power than just forming a link, though. In a normal belongs_to relationship, we use foreign keys for reference in an association. Polymorphic associations come with one huge red flag: compromised data integrity But you can use whatever name that you like. This makes it clear in your relationship which class is polymorphic. The Rails convention for naming a polymorphic association use “- able”. # where owner_type='Order' and owner_id=1 This approach was popularized by Ruby on Rails. There are four different ways:Ī simple approach to connect an order to a resource is to use two columns on the order table: resource_type and resource_id. But it’s not easy to correctly represent the association in a relational database. This is a polymorphic association addresses this issue by condensing this functionality into one association. This can be a problem, for example, when trying to find the owner of an order, we would have to make a point to check both columns to find correct foreign key, rather than relying on one. So, the Order table would have to competing foreign keys: group_id and person_id. Without polymorphic associations, we would have something like this 1 These individuals and groups are not related (other than both being a type of User, maybe), and so they have different data. With polymorphic association, a model can belongs_to several models with a single association.Īs an example, let’s think of a e-commerce site, both individuals and groups can make an order to buy products.