vendredi 10 juillet 2020

Rails - Static constructor in model?

I'm building a Rails API and I'm wondering about design pattern for my User model constructors.

The User model has a has_one relationship to an AuthMehod model that stores its authentication data. AuthMethod has models that inherit from it, for instance PasswordAuth, FacebookAuth and so on.

When a User signs up, I need it to have the AuthMethod created with it and linked to it, so I created static constructors in my User model:

user.rb

class User < ApplicationRecord
  has_one :auth_method, dependent: :destroy
  
  acts_as_paranoid
  validates_as_paranoid
  validates_uniqueness_of_without_deleted :email

  validates_presence_of :first_name, :last_name, :email

  def self.create_with_password_auth!(params)
    create_with_auth_method!(params, PasswordAuth.new(data: params[:password]))
  end

  private

  # Creates a new User and associates an AuthMethod
  # The AuthMethod parameter must be instantiated but not yet saved in the db
  def self.create_with_auth_method!(params, auth_method)
    user = User.create! user_params(params)
    auth_method.user = user
    auth_method.save!
    user
  end

  def self.user_params(params)
    params.slice(:first_name, :last_name, :email)
  end
end

I wonder about the static constructors being the right solution for this. Thing is they're convenient because they can handle a specific logic for the AuthMethod and link it to the newly created User, but is this a good practice? I've tried to find a way to achieve the same behavior with the model callbacks for instance but I'm having trouble to figure out how.

Thanks for reading!

Aucun commentaire:

Enregistrer un commentaire