is there a better DRY code writing for this scope ?

I wrote this scope in my Subdomain model :

scope :in_account, lambda { |account_id|

if account_id == “*”

where(“account_id >= ?”, 0)

else

where(account_id: account_id)

end

}

where account_id == ‘*’ then all subdomain instances are selected

when account_id is given , only subdomain instances in this account are selected

is there a better writing ?

thanks for feedback

I wrote this scope in my Subdomain model :

  scope :in_account, lambda { |account_id|
    if account_id == "*"
      where("account_id >= ?", 0)
    else
      where(account_id: account_id)
    end
  }

where account_id == '*' then all subdomain instances are selected
when account_id is given , only subdomain instances in this account are
selected

is there a better writing ?

you can use scoped instead

account_id == '*' ? scoped : where(account_id: account_id)

Great !

Thanks Jim

Try:

  scope :in_account, lambda { |account_id|
    where(account_id: account_id) if account_id != "*"
  }

If the conditional fails, this will just not interfere with the query.

If it's possible that account_id will be nil or blank (as on a page
accessed w/o passing any params), tack "&& account_id.present?" onto
the conditional.

-Dave