Home > Enterprise >  Select from DB all records or by array if present
Select from DB all records or by array if present

Time:08-15

In RoR app I want to write a model method that will return some records. It should select by ids if ids are present or all records if not

def viewing_duration(ids = nil)
  if ids
    tracks.where(video_id: ids).sum('age(updated_at, created_at)')
  else
    tracks.sum('age(updated_at, created_at)')
  end
end

Question: How I can write query in one line and pass the expression right to where method? Something like this:

tracks.where(video_id: ids.nil? ? 'all' : ids).sum('age(updated_at, created_at)')

CodePudding user response:

Keeping it as more lines probably makes it easier to understand. I suggest keeping it close to as it is while removing repetition:

def viewing_duration(ids = nil)
  if ids
    tracks.where(video_id: ids)
  else
    tracks
  end.sum('age(updated_at, created_at)')
end

If you do want to pass something into where to find all records, you can use an sql statement that will always evaluate to true. For example:

tracks.where(ids.nil? ? '1=1' : { video_id: ids }).sum('age(updated_at, created_at)')

CodePudding user response:

It is not one line, but as idea how to organize your code using chaining

def viewing_duration(ids = nil)
  entities = tracks
  entities = entities.where(video_id: ids) if ids
  entities.sum('age(updated_at, created_at)')
end
  • Related