Kombo
Kombo

Reputation: 2381

Intersection of two arrays coming up empty

I have two arrays and I'm trying to intersect them so I can run a scope, my rails code looks like:

def index 
    @lists = current_user.lists
    @tasks = @lists.collect{|list| list.tasks}
    @search_tasks = Task.search(params[:search])
    @user_tasks = (@tasks & @search_tasks).now_high
end

In my browser I'm getting the following error:

undefined method `now_high' for []:Array

So here's what my scope looks like:

scope :now_high, lambda { where("due_date < ? AND importance = ? AND complete = ?", Date.today + 2.days, 'high', false) }

This scope works when I'm say, doing it just on Task.now_high - the problem I think is my intersect of the two arrays, and I don't know why it's coming up empty everytime.

In the console:

current_user = User.first
 => #<User id: 1, name:...
@lists = current_user.lists
 => [#<List id: 1, name: "Working on sharing lists"... #gets the lists that belong to the user
@tasks = @lists.collect{|list| list.tasks}
 => [[#<Task id: 1, name: "Add create permissions to 'share'",... #gets a collection of all the tasks on the user's lists.
@search_tasks = Task.all
 => [#<Task id: 1, name: "Add create permissions to 'share'"... #simulating a blank search, we have multiple records in common
ruby-1.9.2-p0 > @tasks & @search_tasks
 => [] #why is this empty?

Basically, I could conditionally have it run my scopes only if the array intersect isn't empty. I don't know why though it's coming up empty no matter what?

Upvotes: 2

Views: 594

Answers (1)

lucapette
lucapette

Reputation: 20724

Your @tasks looks like an array of arrays. Try to flatten it before intersection.

Upvotes: 5

Related Questions