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

本文介绍如何在Ruby on Rails中为模型关联定义特定的行为,包括使用module扩展和block块两种方式,并提供具体示例。
前天我们看到了怎样在关联中定义额外的属性,这次我们看看怎样在关联中定义行为
我们以下面的关联为例:
[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]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值