我有这段代码:
@coursesFound = @user.available_courses
@courses = []
for course in @coursesFound do
@courseInGroups = course.user_groups
for group in @courseInGroups do
@group = UserGroup.find group.id
if @group.users.map { |u| u.id }.include? @user.id
@courses << course
end
end
end
我的作品......但有没有办法改进它以获得les和if cascades?
这是available_courses函数。
def available_courses
Course.joins("LEFT JOIN
memberships
ON
memberships.course_id = course_objects.id AND memberships.user_id = " + self.id.to_s + "
JOIN
clients_courses
ON
clients_courses.course_id = course_objects.id
").where("clients_courses.client_id = ? AND memberships.id IS NULL AND course_objects.active = ?", self.client_id, true)
end
通过一些解释进行更新:
是的,我有很多用户组的课程和课程 和一个用户组has_and_belongs到许多用户。
# contains all active courses of the current client
@coursesFound = @user.available_courses
@courses = []
for course in @coursesFound do
# contains a array with all relations between this course. So I got an array of usergroups which should be allowed to see the course
@courseInGroups = course.user_groups
# Here I gonna check if the current user belongs to one of the groups which should be allowed to see the course -- if its true I add this course to the object I return to the view
for group in @courseInGroups do
@group = UserGroup.find group.id
if @group.users.map { |u| u.id }.include? @user.id
@courses << course
end
end
end
更新
我必须改进一些东西才能得到错误结果如下:
@coursesFound = @user.available_courses
@courses = (@coursesFound - @user.user_groups.collect(&:courses).flatten.compact)
但结果是空的......