Reputation: 570
I’m creating a Rails application and I’m having trouble regarding ownership of a record.
I have a many to many relationship and I would like to find the owner/creator of a record.
Models :
class User < ApplicationRecord
has_many :user_accounts
has_many :accounts, through :user_accounts
end
class UserAccount < ApplicationRecord
belongs_to :user
belongs_to :account
end
class Account < ApplicationRecord
has_many :user_accounts
has_many :users, through :user_accounts
end
How could I find the User that actually created the Account ?
I’ve thought about adding a owner_id
field in Account with a belongs_to relationship (e.g. : belongs_to :owner, class_name: 'User' ), but I wanted to know if there was any other way or better way to achieve that ?
Upvotes: 2
Views: 124
Reputation: 4368
The solution you proposed (adding owner_id
to Account
) is a perfectly valid one. Here's a few more.
Add primary
or owner
boolean into UserAccount
. Since you already have a reference to account, it might be better to use that instead of adding another relation.
Another (!dangerous!, but) with no additional columns would be to look for the earliest UserAccount
according to created_at
or similar. I suggest against this though, because any data migration you might do down the line might break this.
Upvotes: 1