Skip to content

Instantly share code, notes, and snippets.

@afcapel
Last active July 3, 2018 19:31
Show Gist options
  • Save afcapel/47fd9fe080c924e9907d11d785833bde to your computer and use it in GitHub Desktop.
Save afcapel/47fd9fe080c924e9907d11d785833bde to your computer and use it in GitHub Desktop.
# app/models/concerns/account_scoped.rb
module AccountScoped
extend ActiveSupport::Concern
included do
belongs_to :account
before_validation :set_current_account, on: :create
before_destroy :belongs_to_current_account
validate :belongs_to_current_account
scope :in_current_account, -> { where(account: Current.account) }
end
private
def set_current_account
self.account = Current.account
end
def belongs_to_current_account
return if Current.account.nil? || account == Current.account
# This will cancel the destroy if the current account doesn't own the record
raise :abort
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment