I’m trying to send my users an email via cron, each with a list of their due tasks. I can send an email to each user with overdue tasks. In my email template, I can display ALL overdue tasks. What I can’t do is list only a specific user’s tasks.
First of all, I have created a scope which finds all the users with due tasks:
Users.rb
scope :tasksdue, lambda {
joins("join tasks on tasks.user_id = users.id").
where("tasks.dueddate >= ? AND tasks.status = ?", Date.today, false).
group("users.id")
}
Also in my users model, I find and send these users an email:
def self.send_reminders
User.tasksdue.find_each do |user|
UserMailer.deliver_task_due user
end
end
And, in my view, I have this:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
<body>
<h1>Hello! <%= @user.name %></h1>
<% User.listtasks.find_each do |task| %>
<li> <%= task.tasks.title %> </li>
<% end %>
</body>
The problem is the tasks due part. I’m calling a scope from my users model:
scope :listtasks, lambda {
joins("join tasks on tasks.user_id = users.id").
where("tasks.dueddate >= ? AND tasks.user_id = ? AND tasks.status = ?", Date.today, :id, false)
}
Using this, I get an error:
undefined method `title’ for #
I’ve also tried calling from Tasks.rb
scope :tasksdue, lambda {
where("dueddate >= ? AND user_id = ? AND status = ?", Date.today, Task.user_id, false)
}
Which complains about user_id.
I can get it to list all global overdue tasks, but not per user.
What do I need to do so it only lists the tasks per user??
— EDIT —
As per advice from @ream88 below, I created two independent scopes and in my Tasks controller for open and overdue:
scope :overdue, lambda { where('dueddate >= ?', Date.today) }
scope :open, where(:status => false)
Now I don’t know how to iterate through these. I have tried this in my actionmailer template but the email is the same for each user…
<% Task.open.overdue.find_each do |task| %>
<%= task.title %>
<% end %>
How can I specify user in this request??
You’re doing a lot of built-in functionally on your own, why? My opinion:
Create a
has_manyassociation in yourUsermodel and the correspondingbelongs_toassociation in yourTaskmodel (if not already done):And add following scopes to
Task:And now you’re able to access overdue tasks for a specific user via:
user.tasks.open.overdue. (You can probably create only one scope in yourTaskmodel including both search criteria, but my opinion is to split my code into the smallest pieces possible.)