Model 如何在rails 3中构建作用域记录?

Model 如何在rails 3中构建作用域记录?,model,ruby-on-rails-3,Model,Ruby On Rails 3,我有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, :cond

我有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
班级学校“Person”,:include=>:roles,:conditions=>[“roles.name=?”,“Teacher”]
有很多:学生,:class\u name=>“Person”,:include=>:roles,:conditions=>[“roles.name=?”,“Student”]
结束
类Person“教师”)
范围:student,其中(:name=>“student”)
结束
获取记录效果很好(如school.teachers或school.student)

但是如何制作呢

  • 学校、教师、建筑 学校。教师。新)分配角色 “老师”
  • 学校、学生、建筑 学校。学生。新)分配角色 “学生”

  • 我假设您希望为给定的学校实例创建一个新教师或学生

    如果是这种情况,你可以做两件事中的一件。您可以在学校模型中创建两种方法来创建新的学生和教师,也可以简单地调用教师或学生模型上的构造函数并在学校中通过。例如:

    将方法添加到学校模型(选项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 )