Add Behavior to Active Record Associations
先贴上数据迁移代码
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
有两种方式在模型关联上添加额外的方法
第一种方法
先建立一个module
module GradeFinder
def below_average
find(:all, :conditions => ['score < ?' , 2])
end
end
然后拓展mode
require "grade_finder"
class Student < ActiveRecord::Base
#注意:extend
has_many :grades, :extend => GradeFinder
end
第二种较简单 直接把定义的方法通过'块'赋给has_many关系的声明
class Student < ActiveRecord::Base
has_many :grades do
def below_average
find(:all, :conditions => ['score < ?' , 2])
end
def foo
raise self.inspect
end
end
end
chad> ruby script/console
>> Student.find(1).grades.below_average
=> [#<Grade:0x26aecc0 @attributes={"score"=>"1", "class"=>"Algebra",
"student_id"=>"1", "id"=>"1"}>]
之所以可以动态的在关系声明时添加方法是因为当调用grade()方法时返回的是ActiveRecord::Associations::AssociationProxy实例他介于这里是Student 和Grade 之间 真正的例如 find( ), count( ), create( )方法都是在关系(如has_many)定义的,这个关系的调用返回的是一个代理再由这个代理执行具体的mode的方法 (find( ), count( ), create( )...),因此可以在关系中扩展方法。就像继承扩展一样
分享到:
相关推荐
Ruby三神书之一(其余的两本是Agile.Web.Development.with.Rails和Ruby For Rails,在我的资源列表也有) Rails is large, powerful, and new. How do you use it effectively? How do you harness the power? And, ...
顾名思义,就是讲rails的小技巧,给你上rails的大餐,都是大牛们写的文章,对于想掌握常用技巧的开发者很有帮助
Rails Recipes Final.pdf
Rails Recipes
Ruby三神书之一(其余的两本是Agile.Web.Development.with.Rails和Ruby For Rails,在我的资源列表也有) Rails is large, powerful, and new. How do you use it effectively? How do you harness the power? And, ...
"Advanced Rails Recipes" is filled with pragmatic recipes you'll use on every Rails project. And by taking the code in these recipes and slipping it into your application you'll not only deliver your...
"Advanced Rails Recipes" is filled with pragmatic recipes you'll use on every Rails project. And by taking the code in these recipes and slipping it into your application you'll not only deliver your...
Advanced Rails Recipes 正式版。 不要资源分,免费提供,要下的赶快哦。。。
Rails.Recipes.Rails.3.Edition.和源码
像所有好的食谱一样,Rails Recipes 提供各种主题的不同处方集,例如用户界面、控制器、数据库、测试、蓝图和电子邮件。它也将标签分配给每个处方,以确定该处方涵盖什么内容。
官方推荐的Ruby On Rails书籍,Rails Recipes 2012最新版,英文, 专业ruby程序员必备
ruby rails web development recipes
Written for novice to intermediate Rails developers, Rails Recipes: Rails 3 Edition is packed with solutions to 70 of the most vexing problems you’re likely to face on the job. From building custom ...
专业RoR参考手册..
Ruby Recipes A Problem-Solution Approach 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书
Rails_Recipes_with_Source_Code
Pragmatic.Bookshelf.Advanced.Rails.Recipes.May.2008