2014-01-12 161 views
0

我有我的Rails應用程序完全正常工作(有一段時間了)許多一對多關係的能力一對多的關係。許多與設置狀態(活動)

教師有很多學校(通過SchoolsToInstructorsAssociations) 學校有許多教師(通過SchoolsToInstructorsAssociations)

在這個時候,我想有另外一個「激活狀態」的能力,簡單地添加或刪除講師來自學校或教師的學校。

我想講師在稍後點完全被移除(或激活)之前被設置爲不活動的。

我首先想到的是「活躍」布爾添加到關係模型(SchoolsToInstructorsAssociations),但有訪問此屬性更新或查詢它)沒有簡單的方法。

我的第二個想法是簡單地創建與「活躍」屬性的另一個關係模型,但它是多餘的和額外的東西我必須跟蹤。

也許自定義多到多​​模塊?創建SchoolsToInstructorsAssociations控制器?

class Instructor < ActiveRecord::Base 
    has_many :schools_to_instructors_association 
    has_many :schools, :through => :schools_to_instructors_association 
end 

class School < ActiveRecord::Base 
    has_many :schools_to_instructors_association 
    has_many :instructors, :through => :schools_to_instructors_association 
end 

class SchoolsToInstructorsAssociation < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :school 
end 

我還計劃在教師「活躍」狀態發生變化或教師被移除或添加到學校時創建歷史記錄。不問如何做到這一點,但想知道它是否可以用來跟蹤教練'積極'的狀態。

class SchoolsController < ApplicationController 
    def instructors_index 
    @school = School.find(params[:id]) 
    instructors = find_instructors 
    @active_instructors = instructors[0] 
    @inactive_instructors = instructors[1] 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @schools } 
    end 
    end 

    private 

    def find_instructors 
    active = []; inactive = [] 
    @school.instructors.each do |s| 
     if SchoolsToInstructorsAssociationRecord.where(user_id: s, school_id: @school)[0].active? 
     active << s 
     else 
     inactive << s 
     end 
     return [active, inactive] 
    end 
    end 
end 

class SchoolsToInstructorsAssociationRecord < ActiveRecord::Base 
    default_scope order('created_at DESC') 
    attr_accessor :user_id, :school_id, schools_to_instructors_association_id, :active 
end  
+1

究竟什麼是你的問題嗎? – phoet

回答

1

聽起來像你可以完成你想要做的事情與範圍。添加一個布爾值列「主動」,你的「導師」類描述,那麼你可以添加範圍爲它:

class Instructor < ActiveRecord::Base 
    ... 
    scope :active, -> { where(active: true) } 
    scope :inactive, -> { where(active: false) } 
    ... 
end 

那麼對於一個給定的School,你可以得到的有效(或無效)導師那所學校:

@school.instructors.active 
=> SELECT "instructors".* FROM "instructors" WHERE "instructors"."school_id" = <id> AND "instructors"."active" = 't' 

如果你想要做的所有非活動指導員某些操作(如消滅他們,作爲一個例子),你可以這樣做:

Instructor.inactive.map(&:destroy) 

,您可以Ø f課程爲InstructorSchool類編寫任何想要的自定義方法。