每天一剂Rails良药之Adding Behavior to Your ActiveRecord Association

前天我们看到了怎样在关联中定义额外的属性,这次我们看看怎样在关联中定义行为
我们以下面的关联为例:
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

需要注意的是我们调用student.grades()方法时返回的是ActiveRecord::Associations::AssociationProxy而不是Array,而AssociationProxy可以访问find(),count(),create()等Model的方法
我们有两种方法在关联中定义行为:
1,通过module来定义行为
lib/grade_finder.rb
module GradeFinder
  def below_average
    find(:all, :conditions => ['score < ?', 2])
  end
end


app/models/student.rb
require "grade_finder"
class Student < ActiveRecord::Base
  has_many :grades, :extend => GradeFinder
end


2,通过block来定义行为
app/models/student.rb
class Student < ActiveRecord::Base
  has_many :grades do
    def below_average
      find(:all, :conditions => ['score < ?', 2])
    end
  end
end

你可能感兴趣的:(UP,Rails,ActiveRecord)