I've spent all day making this work and to me, the results are a little ugly. Surely there must be a better way and almost certainly, I don't know about it.
I have a model - Task, which has_many (or none!) TimeLogs
until now I used an instance method to tell whether it was started? or !started?
def started?
time_logs.length > 0
end
but when creating scopes, I found I couldn't implement this method into the query. If there is a way, I'd really love to know because I have some similar problems on the horizon.
The way I did solve this was to refactor it into a proper database scope with a join:
scope :started, joins(:time_logs).uniq
pretty neat, how about the inverse?
scope :not_started, joins("LEFT OUTER JOIN time_logs ON tasks.id = time_logs.task_id").where("time_logs.task_id is null")
bleaurgh. Surely not?
It works, but I keep hoping I'll come across a NOT operator that would return everything that the first scope didn't, or a "Task.all - Task.started" kind of solution.
我真的不认为有更好的解决方案,但这应该有很好的表现:
scope :not_started, where("ID NOT IN (SELECT task_id FROM time_logs)")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.