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)')
2
Answers
Keeping it as more lines probably makes it easier to understand. I suggest keeping it close to as it is while removing repetition:
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:
It is not one line, but as idea how to organize your code using chaining