我有两个数组,我试图将它们相交,以便我可以运行一个范围,我的 Rails 代码如下所示:
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
在我的浏览器中,我收到以下错误:
[]:Array 的未定义方法“now_high”
这就是我的范围:
scope :now_high, lambda { where("due_date < ? AND importance = ? AND complete = ?", Date.today + 2.days, 'high', false) }
当我说这个范围有效时,只需在 Task.now_high 上执行即可 - 我认为问题是两个数组的交集,我不知道为什么它每次都为空。
在控制台中:
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?
基本上,只有当数组相交不为空时,我才能有条件地让它运行我的范围。我不知道为什么无论如何它都是空的?
最佳答案
你的@tasks看起来像一个数组的数组。尝试flatten它在交叉点之前。
关于ruby-on-rails - 两个数组的交集为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245125/