How to build scoped record in rails 3?
i have 3 models Schools, People and R开发者_StackOverflow中文版oles
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
fetching records works fine (like school.teachers or school.students)
but how to make
- school.teachers.build (or school.teachers.new) assign role 'Teacher' ?
- school.students.build (or school.students.new) assign role 'Student' ?
I'm assuming that you want to create a new Teacher or Student for a given School instance.
If this is the case you can do one of two things. You can create two methods in the School model to create new students and teachers or you can simply call the constructor on the Teacher or Student model and pass in the school. For example:
Add methods to School model (option 1):
def new_teacher( put_params_for_teacher_here, school )
return Teacher.new( put_passed_in_params_here, :school => school
end
# Repeat for new_student
Pass school in during Teacher/Student creation (option 2):
Teacher.new( params_for_teacher, :school => school )
The obvious route is to simply pass in the school when creating your Teacher/Student objects.
精彩评论