2014-01-12 2 views
0

내 Rails 응용 프로그램에서 (지금 당분간) 다 대다 관계가 있습니다.상태를 설정할 수있는 많은 관계 (활성)

강사가 많은 (SchoolsToInstructorsAssociations을 통해) 학교 학교가 있습니다 (SchoolsToInstructorsAssociations을 통해) 많은 강사 이때

을 가지고, 단순히 추가하거나 강사를 제거하는 이외에 "활성 상태"가 할 수있는 능력을 싶습니다 강사의 학교 또는 학교에서.

강사를 나중에 비활성 상태로 설정하거나 나중에 다시 제거하기를 원합니다.

내 첫 번째 생각은 관계형 모델 (SchoolsToInstructorsAssociations)에 '활성'부울을 추가하는 것이지만이 속성에 액세스하여이를 업데이트하거나 쿼리하는 간단한 방법은 없습니다.

나의 두 번째 생각은 'active'속성을 가진 또 다른 관계 모델을 간단하게 만드는 것이지만 중복되고 여분의 무언가를 추적해야합니다.

맞춤형 many-to-many 모듈일까요? 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를 들어, 당신이 활성 (또는 비활성) 강사를 얻을 수 있습니다

: 당신은 '강사'클래스에 기재 한 바와 같이, 당신은 그것을 위해 범위를 추가 할 수있는 '활성'에 대한 부울 열을 추가 오

Instructor.inactive.map(&:destroy) 

그리고 당신은 할 수 있습니다 그 학교 : 당신이 (같은 예로서, 그들을 파괴) 모든 비활성 강사에 대한 몇 가지 작업을하고 싶었다 경우

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

, 당신은 할 수 f Instructor 또는 School 클래스에 대해 원하는 맞춤법을 작성하십시오.