0

Have an app where current_user can be a Client or and Admin. A Client can have many Accounts and an AccountStatement belongs to both the Account and the Client.

However there are some auto generated statements that we don't want to show the clients. I'd like to add a model scope of some kind that would look something like

    def account_statements
        if current_user.is_a?(Client)
            super.where(auto_generated: false)
        else
            super
        end
    end

so if I ran .account_statements on a valid instance of Account or Client it would only return a subset of the statements if the current_user is a Client, but all of them if the current_user is an Admin. Is there any way to do this?

SomeSchmo
  • 665
  • 3
  • 18

1 Answers1

0

Just give each class its own method:

class Admin < ApplicationRecord
  ...
  def account_statements
    AccountStatement.all
  end
end

class Client < ApplicationRecord
  ...
  def account_statements
    AccountStatement.where(auto_generated: false)
  end
end

If you need Client to have a defined relationship to AccountStatement, things get a little more tricky:

class Client < ApplicationRecord
  has_many :account_statements

  # this method will supersede the relationship
  def account_statements
    ...
  end
end

In which case, you can either:

  1. use a different name for the method

  2. use this cool relationship-with-scope trick to do something like this:

class Client < ApplicationRecord
  has_many :account_statements, -> { without_auto_generated }
end

class AccountStatement < ApplicationRecord
  belongs_to :client
  belongs_to :account

  scope :without_auto_generated, -> { where(auto_generated: false) }
end
Chiperific
  • 4,428
  • 3
  • 21
  • 41