nazshal
nazshal

Reputation: 65

Reducing an if statement to generate a mongoid query

I have the code below and I would like to know if it possible to reduce the code.

bank_accounts = self.client_bank_account_id.nil? ? self.client.bank_accounts : self.client.bank_accounts.where(_id: self.client_bank_account_id)

I only need the where call when client_bank_account_id is not nil.

Upvotes: 0

Views: 29

Answers (2)

Yule
Yule

Reputation: 9764

That depends, are you going for 'shortest code possible' code golf style or simply the nicest, possibly easier reading code.

I'd go with:

bank_accounts = client.bank_accounts
bank_accounts = bank_accounts.where(_id: client_bank_account_id) if client_bank_account_id

Notes:

  • You don't need 'self'.
  • nil checks are probably not the best way to go.
  • Lazy loading should stop there being two calls to the db here

Upvotes: 0

Leo Brito
Leo Brito

Reputation: 2051

Not exactly shorter, but I'd say its more readable:

bank_accounts = self.client.bank_accounts
bank_accounts = bank_accounts.where(_id: self.client_bank_account_id) unless self.client_bank_account_id.nil?

Upvotes: 1

Related Questions