2017-09-01 44 views
0

我有了很多很多的關聯Rails的可變數據正在改變

學生 項目

通過表student_projects

student = Student.find(1) 
old_projects = student.projects 

#Now Iam calling function that will create projects 
create_projects 

student = Student.find(1) 
new_projects = student.projects 
newly_added_projects = new_projects - old_projects 

舊項目是空連接的兩個表,new_projects不

我把創建之前和之後的記錄器語句(new_projects = students.projects),然後我可以看到di fference。

但是當我後,方可行(newly_added_projects = new_projects - old_projects)記錄器語句檢查old_projects,new_projects,newly_added_projects

然後old_projects等於new_projects

有人可以幫我在這

+2

Rails試圖推遲數據庫訪問,直到實際需要的數據。我不確定Rails 3的行爲如何,但我的猜測是'old_projects = student.projects'不會返回一個數組,而是返回某種代理。並且這兩個查詢都是在調用'-'後執行的(所以兩者都返回相同的結果)。嘗試通過添加'to_a'來執行查詢,即'old_projects = student.projects.to_a' – Stefan

+0

您正在使用的是什麼Rails版本? – Mohanraj

+0

Stefan - 感謝您的工作 –

回答

1

我建議你去之前並創建新項目後,收集項目IDS和減去舊項目ID和新項目的ID,如下面的ID,

student = Student.find(1) 
old_project_ids = student.projects.map(&:id) # You may use student.project_ids 

#Now Iam calling function that will create projects 
create_projects 

student = Student.find(1) 
new_project_ids = student.projects.map(&:id) 
newly_added_project_ids = new_project_ids - old_project_ids 

否則你可能對象轉換old_projects從積極的記錄關係,像下面的普通紅寶石陣列,

student = Student.find(1) 
old_projects = student.projects.to_a 

#Now Iam calling function that will create projects 
create_projects 

student = Student.find(1) 
new_projects = student.projects_to_a 
newly_added_projects = new_projects - old_projects 
+0

如果你只是對id感興趣,你應該使用'pluck(:id)'。 – Stefan

+0

是的,我們可以使用拔毛。謝謝。 – Mohanraj

-1
student = Student.find(1) 
old_projects = student.projects 

newly_added_projects = create_projects # return newly projects from method itself. 

def create_projects 
    projects = [] 

    #add newly created projects in projects array and return at the end. 
    return projects 
end 

做那樣的事情。無需從舊的計算它,您已經在您的create_projects方法項目。

+0

這與問題無關,因爲@Stefan在評論中解釋說與推遲SQL查詢執行有關。 – mudasobwa