2
我有兩個數組,我想他們相交,這樣我就可以運行一個範圍,我的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
在我的瀏覽器,我發現了以下錯誤:
未定義的方法`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?
基本上,我可以有條件地有它運行我只範圍如果數組相交不爲空。我不知道爲什麼它會變成空的,不管是什麼?
即使它不是空的,你的代碼也不會工作。您的錯誤狀態:[]:Array的未定義方法'now_high'。這意味着now_high沒有爲Array定義爲空或滿。 – ayckoster
你是對的,我的一個追蹤思路。我會重構並在這裏發佈我的工作解決方案。謝謝 – Kombo
好吧,只是做了一點改變來解決這個問題。我現在在搜索方法之前調用範圍。所以它看起來像:@search_tasks = Task.now_high.search(params [:搜索]) - 感謝幫助ayckoster – Kombo