has_many,class_name,foreign_key,include?,through,source


has_many的使用技巧


+ def main_manager
+    creator
+  end
+
   module UserMethods
     def self.included(base)
-      base.has_many :course_subjects
+      base.has_many :created_course_subjects, :class_name => "CourseSubject",
+                    :foreign_key => :creator_id
     end
   end


     def add_course(course, user)
-      return if _check_user(user) || self.course_subject_courses.by_course(course).first
+      return if !self.is_manager?(user) || self.courses.include?(course)
       self.course_subject_courses.create(:course => course, :manager_id => user.id)
     end


     def remove_course(course, user)
-      return if _check_user(user)
-      course_subject_course = self.course_subject_courses.by_course(course).first
-      course_subject_course.destroy if course_subject_course
+      return if !self.is_manager?(user)
+      self.course_subject_courses.by_course(course).destroy_all
+    end
+
+    def is_manager?(user)
+      self.main_manager == user || self.secondary_managers.include?(user)
     end

-    private
-      def _check_user(user)
-        course_subject_course       = self.creator.id == user.id
-        course_subject_managership  = self.course_subject_managerships.by_user(user).first
-        return true if !(course_subject_course || course_subject_managership)
-      end
   end



   def user_check
     if self.user_id == self.course_subject.creator_id
-      errors.add :base, 'course_subject_managerships.user_id == course_subject.creator_id' 
+      errors.add :base, '不能把主管理员设置为副管理员'
     end
   end



     def self.included(base)
       base.has_many :course_subject_managerships
-      base.has_many :managers, :through => :course_subject_managerships, :source => :user
+      base.has_many :secondary_managers, :through => :course_subject_managerships, :source => :user
     end



     def remove_manager(user)
-      course_subject_managership = self.course_subject_managerships.by_user(user).first
-      course_subject_managership.destroy if course_subject_managership
+      self.course_subject_managerships.by_user(user).destroy_all
     end



     def self.included(base)
       base.has_many :course_subject_managerships
        # user作为副管理员的课程主题
-      base.has_many :course_subjects, :through => :course_subject_managerships
+      base.has_many :manage_course_subjects, :through => :course_subject_managerships, :source => :course_subject
     end


你可能感兴趣的:(include,source,has_many,through,class_name)