0

In my Rails application, I have a Project model with an associated Task model (Project has many tasks). Each Task has a field called parent_task_id that links it to a task from a previous version. When a new Task is created in a new version, it references itself by setting parent_task_id equal to its own task_id.

I’m trying to write a query to find all tasks in a new Project version where parent_task_id is equal to task_id—this would identify records that were newly added in the latest version.

However, my current query is returning an empty array, even though I know there are matching records. Here’s what I have so far: new_tasks = new_project.tasks.where('tasks.task_id = tasks.parent_task_id')

new_tasks = new_project.tasks.where('tasks.task_id = tasks.parent_task_id')

expected output

{
  task_id: 64741,
  parent_task_id: 64741,
  # other attributes...
}

How can I correctly structure this ActiveRecord query to find tasks where parent_task_id equals task_id? Is there a special consideration in ActiveRecord for self-referencing conditions like this?

Any help or tips would be much appreciated. Thank you!

1 Answer 1

0

Use Arel, which is built in to Rails, to compose your query instead of the query string:

table = Arel::Table.new(:tasks)
new_tasks = new_project.tasks.where(t[:task_id].eq(t[:parent_task_id]))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.