0

I have the following scope:

scope :task_based, ->(dept, number){ joins(:task).where('tasks.department = ? and tasks.number = ?', dept, number)}

Which works great, except occasionally I need to say something to the effect of where tasks.number is equal to 123 OR 456

I know ActiveRecord lets me do where(number: [123, 456]) but since this is a JOIN, that doesn't seem to work.

So how could I pass an array on that scope? It won't always be an array, but needs to account for when it is.

2 Answers 2

1

Here is what you need to do :

scope :task_based, ->(dept, number){ joins(:task).where('tasks.department = ? and tasks.number in (?)', dept, number)}

The above scope would work on both cases i.e., number as integer or an array of integers.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to bust out some duck typing for this one

                                   # I like to use do/end for multi-line blocks, but that is purely a stylistic choice
scope :task_based, ->(dept, number) do 

  return joins(:task).where('tasks.department = ? AND tasks.number IN ?', dept, number) if number.is_a? Array

  return joins(:task).where('tasks.department = ? and tasks.number = ?', dept, number) if number.is_a?

end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.