mardi 20 octobre 2015

Rails model to handle composite records

The first form of database normalisation is to hold potentially null fields in a second table, and join these in when they are referred to. The SQL would look something like this.

SELECT A.*, DA.* FROM ANIMALS A
INNER JOIN DOG_ATTRIBUTES DA ON DA.ANIMAL_ID = A.ID

This is pretty common for large databases to use, so only a dog would have the dog-specific attributes. Now I know this could be implemented as a has_one relationship, e.g.

class Dog < Animal
  has_one :dog_attribute
end

If it was a read-only model, I could implement the above SQL as a view, and just refer to the DOGS view in my Dog model.

Is there a way I can treat the composite Dog object (with attributes from the ANIMALS table and the DOG_ATTRIBUTES table) as a single model, placing attributes of both into forms, saving them as one command and retrieving the attributes of both?

Aucun commentaire:

Enregistrer un commentaire