2011-01-03 5 views
1

私は3つのモデル学校、(school.teachersまたはschool.studentsのように)正常に動作しますレール3にスコープ付きレコードを作成するにはどうすればよいですか?

しかし

    の作り方レコードをフェッチ 人々役割

    class School < ActiveRecord::Base 
    
        has_many :teachers, :class_name => "Person", :include => :roles, :conditions => ["roles.name = ?",'Teacher'] 
        has_many :students, :class_name => "Person", :include => :roles, :conditions => ["roles.name = ?",'Student'] 
    end 
    
    class Person < ActiveRecord::Base 
        has_and_belongs_to_many :roles 
        belongs_to :school 
        scope :teachers, joins(:roles) & Role.teacher 
        scope :students, joins(:roles) & Role.student 
    end 
    
    class Role < ActiveRecord::Base 
        has_and_belongs_to_many :persons 
        validates_presence_of :name 
    
        def self.sanitize role 
        role.to_s.humanize.split(' ').each{ |word| word.capitalize! }.join(' ') 
        end 
    
        scope :teacher, where(:name => 'Teacher') 
        scope :student, where(:name => 'Student') 
    
    end 
    

    を持っています

  1. school.teachers.build(または school.teachers.new)ロールを割り当てる 「先生」?
  2. school.students.build(または school.students.new)ロールを割り当てる 「学生」ですか?

答えて

0

私は、あなたが指定されたSchoolインスタンスに対して新しい教師または生徒を作成したいと仮定しています。

この場合、次の2つのうちのいずれかを実行できます。 Schoolモデルで2つのメソッドを作成して新しい生徒と教師を作成するか、単に教師または生徒のモデルでコンストラクタを呼び出して学校に渡すことができます。たとえば:

は、学校のモデル(オプション1)にメソッドを追加します:教師/学生の作成(オプション2)の間で

def new_teacher(put_params_for_teacher_here, school) 
    return Teacher.new(put_passed_in_params_here, :school => school 
end 

# Repeat for new_student 

パス学校:

Teacher.new(params_for_teacher, :school => school) 

明白なルートは、単純にあります教師/生徒のオブジェクトを作成するときに学校を通過します。

関連する問題