Obromios
Obromios

Reputation: 16403

Make a sql limit query work for all records in table

How do you specify the number to a sql limit method such that the limit is actually all records. I want to have a scope with a flexible limit e.g. scope :females, ->(n) {where(gender: 'Female').limit(n). Using this scope how do I specify all records? Is there a better way than females(Model.all.count)?

Upvotes: 0

Views: 73

Answers (2)

Vijay Agrawal
Vijay Agrawal

Reputation: 1693

Do females(nil) to not have limit clause applied. This works because limit(nil) applies no limit.

Upvotes: 1

Evan
Evan

Reputation: 571

Maybe this helps:

scope :females, ->(n=nil) do
  if n.present?
    where(gender: 'Female').limit(n)
  else
    where(gender: 'Female')
  end
end

Then:

Yourclass.females(10)   #=> reuturn 10 female records
Yourclass.females       #=> reuturn all female records

Upvotes: 1

Related Questions