tomichj / invitation

A Rails gem that can send 'scoped' invitations
MIT License
75 stars 28 forks source link

How should I add through model attributes? #26

Closed natecox closed 2 years ago

natecox commented 5 years ago

I have a need for a through table containing user status, as such:

class User < ApplicationRecord
  include Invitation::User

  has_many :organization_memberships, dependent: :destroy
  has_many :organizations, through: :organization_memberships

  devise :database_authenticatable, :recoverable, :rememberable, :validatable, :trackable, :registerable
end
class OrganizationMembership < ApplicationRecord
  belongs_to :user
  belongs_to :organization

  enum status: { "Owner": 0, "Admin": 1, "Member": 2 }
end
class Organization < ApplicationRecord
  has_many :organization_memberships, dependent: :destroy
  has_many :users, through: :organization_memberships, source: :user

  alias_attribute :members, :users

  validates :name, presence: true

  invitable named_by: :name
end

When I invite a user to an organization, I need to store what their status is going to be. My first assumption is that I should add a field to the Invite model, but I don't have direct access to that model so I'm not quite sure what the correct process should be here.

Should I just monkey patch the model, and override the controller for create and the form? Or, is there a simpler way to handle this?

Thanks for the help in advance, still fairly new to rails here, so slightly out of my element for problem solving.

natecox commented 5 years ago

As a minor update, I was able to solve this very manually. Essentially I created a migration to add a field to the Invite model to hold the member status value, updated the form to include a select field containing the enum values, updated the controller/hooks/etc to override the creation process and pass over that stored value to the through model.

It works, but this feels very cumbersome. I had to override basically every part of the invitation flow to make this happen, which admittedly might be because I'm still fairly new to rails. I'd still welcome a more experienced perspective.