I have three tables: groups, memberships, and users. When a user creates a group I need to make sure that a membership in that group is also created. I have considered using transactions but I keep seeing that these are being deprecated. Is there some other practice that is simpler or preferred?
Groups:
name
description
owner_id (user_id)
[has_many :users, through :memberships]
[has_many :memberships]
Since Memberships is essentially a join table with an extra attribute,
and I see that you already have your :through relationships defined,
simply doing
The key is that @user.owned_groups as set up here are the groups where
the group's owner_id == @user.id and @user.groups are the groups that
the @user is a member of via the memberships join table.
I have three tables: groups, memberships, and users. When a user
creates a group I need to make sure that a membership in that group is
also created. I have considered using transactions but I keep seeing
that these are being deprecated.
IIRC transactions aren't deprecated only the form where the rollback not
only applies to the DB but to the ActiveRecord::Base objects too.
The day ActiveRecord::Base completely removes transaction support is the
day someone will fork it or provide the feature as a plugin
There are two relationships between user and group:
One is a many to many relationship (the concept of membership), one is
a one to many (the concept of ownership).
The many to many is already expressed via a has_many :through with a
Membership join model. This is roughly equivalent to a habtm but also
allows attributes on the join (like the confirmed_at timestamp)
because the join table is represented as a first order class via the
Membership model. Habtm would not be sufficient for this relationship.
The other is the "ownership" of the group, as expressed with the
owner_id foreign key. This is a completely separate relationship and
needs to be specified as a has_many/belongs_to.
I hope this better explains the reasoning behind the relationships I
outlined above.