mardi 22 mai 2018

Modeling has_one "active" child among has_many children

I have a model:

class Group < ActiveRecord::Base
  has_many :progressions
  has_one :active_progression, class_name: "Progression"
end

And the child:

class Progression < ActiveRecord::Base
  belongs_to :group
end

I know that convention says I should create a separate foreign key inside Progression to associate the active progression with the Group's id (as that is how has_one works).

However, IMHO, it makes more logical sense to store the 'active' child's id in the Group model. Edit: The reasoning is that storing the Group id in the Progression model as active_group_id or something similar is semantically confusing and opens the possibility of having multiple active progressions associated with a Group, which is obviously incorrect.

I have read several posts where people confuse the underlying has_one meaning, assuming it does the same thing as belongs_to but for the parent. I know this is not the case. has_one does the opposite of belongs_to, i.e. looking for the key in the counterpart instead of the calling model.

If Rails does not provide a method for creating an association of this nature, what is the most Railsy solution?

Aucun commentaire:

Enregistrer un commentaire