前天我们看到了怎样在关联中定义额外的属性,这次我们看看怎样在关联中定义行为
我们以下面的关联为例:
[code]
class AddStudentsTables < ActiveRecord::Migration
def self.up
create_table :students do |t|
t.column :name, :string
t.column :graduating_year, :integer
end
create_table :grades do |t|
t.column :student_id, :integer
t.column :score, :integer # 4-point scale
t.column :class, :string
end
end
def self.down
drop_table :students
drop_table :grades
end
end
class Student < ActiveRecord::Base
has_many :grades
end
class Grade < ActiveRecord::Base
end
[/code]
需要注意的是我们调用student.grades()方法时返回的是ActiveRecord::Associations::AssociationProxy而不是Array,而AssociationProxy可以访问find(),count(),create()等Model的方法
我们有两种方法在关联中定义行为:
1,通过module来定义行为
lib/grade_finder.rb
[code]
module GradeFinder
def below_average
find(:all, :conditions => ['score < ?', 2])
end
end
[/code]
app/models/student.rb
[code]
require "grade_finder"
class Student < ActiveRecord::Base
has_many :grades, :extend => GradeFinder
end
[/code]
2,通过block来定义行为
app/models/student.rb
[code]
class Student < ActiveRecord::Base
has_many :grades do
def below_average
find(:all, :conditions => ['score < ?', 2])
end
end
end
[/code]
我们以下面的关联为例:
[code]
class AddStudentsTables < ActiveRecord::Migration
def self.up
create_table :students do |t|
t.column :name, :string
t.column :graduating_year, :integer
end
create_table :grades do |t|
t.column :student_id, :integer
t.column :score, :integer # 4-point scale
t.column :class, :string
end
end
def self.down
drop_table :students
drop_table :grades
end
end
class Student < ActiveRecord::Base
has_many :grades
end
class Grade < ActiveRecord::Base
end
[/code]
需要注意的是我们调用student.grades()方法时返回的是ActiveRecord::Associations::AssociationProxy而不是Array,而AssociationProxy可以访问find(),count(),create()等Model的方法
我们有两种方法在关联中定义行为:
1,通过module来定义行为
lib/grade_finder.rb
[code]
module GradeFinder
def below_average
find(:all, :conditions => ['score < ?', 2])
end
end
[/code]
app/models/student.rb
[code]
require "grade_finder"
class Student < ActiveRecord::Base
has_many :grades, :extend => GradeFinder
end
[/code]
2,通过block来定义行为
app/models/student.rb
[code]
class Student < ActiveRecord::Base
has_many :grades do
def below_average
find(:all, :conditions => ['score < ?', 2])
end
end
end
[/code]