I have models as follows: User has_many goals, Goal has_many tasks, Task has_many day_tasks. I’m trying to write a method which finds all day_tasks that
- belong to a certain user
- have
:target_date == Date.today(target_date is a column in the day_tasks table).
I want to put the results into the @day_tasks array.
my code:
@user = current_user
@day_tasks = DayTask.find { |x| x.task.goal.user == @user && x.target_date == Date.today }
This code only returns the first record that matches these criteria. I’ve also tried using the DayTasks.where method with the same code in the braces, but I just a “Wrong number of arguments ( 0 for 1 )” error. Could someone explain why my method only returns the first occurrence and what exactly the difference is between .find and .where?
You wrote this:
The
findmethod here is actually falling back toEnumerable‘sfind, which is an alias fordetect, which takes a block and will return the first element in that collection that matches the block’s conditions or will returnnil.In order to fix this, you’re going to need to use ARel’s query stuff that’s built-in to ActiveRecord.
The
joinsmethod here will join the tables that match the association names in yourDayTaskmodel and related models. This means you must have ataskassociation on theDayTaskmodel and on that model have agoalsassociation and on the goals model have one foruser.The
wherewill then construct an SQL condition that will query the joins to find all records that belong to a user and have atarget_dateof today.