Rails变量数据正在发生变化

时间:2017-09-01 09:19:33

标签: ruby-on-rails ruby ruby-on-rails-3

我有两张桌子,里面有很多关联

的学生 项目

通过表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不是

我在创建之前和之后放置了logger语句line(new_projects = students.projects),然后我可以看到区别。

但是当我把logger语句放在line(new_added_projects = new_projects - old_projects)之后检查old_projects,new_projects,newly_added_projects

然后old_projects等于new_projects

有人可以帮助我吗

2 个答案:

答案 0 :(得分:1)

我建议你在创建新项目之前和之后收集项目ID,并减去旧项目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 对象从活动记录关系转换为纯ruby数组,如下所示

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

答案 1 :(得分:-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方法中有项目。