This is a classic User → Membership → Group example with some twist: User is a member of a single Group at any given
time. But I want to keep the history which Group the User was a member of.
I am looking for a proper way of doing it.
This is how I think models should look like:
#user.rb
Class User < ActiveRecord::Base
has_many :memberships
has_many :groups, through: :memberships
#membership.rb
Class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
#group.rb
Class Group < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
Obviously we need date_from attribute in memberships to keep a track on when the user joined the group.
Creating/Updating is working out of the box. It’s querying data I have trouble with.
Now it is easy to get the last group the user is a member of:
#user.rb
…
def latest_group
memberships.order(:date_from).last.group
end
Similarly you can get latest user for a group.
But how to get all users currently belonging to group? Furthermore how to get all the users belonging to group at given date?