我碰到一個問題,參考這本書 RailsRecipes 3 關於 Add Behavior to Active Record Associations 如何新增行為到 AR 去。
底下是實行的步驟:
用 scaffold 建立 studnet 模型包括 :name :graduating_year assoc_proxies$ rails g scaffold student name:string graduating_year:integer 用 scaffold 建立 grade 模型包括 :score :class_name assoc_proxies$ rails g scaffold grade score:integer class_name:string
assoc_proxies$ rails c
Loading development environment (Rails 3.0.10)
ruby-1.9.2-p290 :002 > me = Student.create(:name => "idarfan", :graduating_year => 2120)
=> #<Student id: 2, name: "idarfan", graduating_year: 2120, created_at: "2012-09-07 10:52:42", updated_at: "2012-09-07 10:52:42">
ruby-1.9.2-p290 :003 > me.grades.create(:score => 3, :class_name => "Algebra")
=> #<Grade id: 2, student_id: 2, score: 3, class_name: "Algebra", created_at: "2012-09-07 10:53:06", updated_at: "2012-09-07 10:53:06">
ruby-1.9.2-p290 :004 > s_all = Student.all
=> [#<Student id: 1, name: "Chad", graduating_year: 2020, created_at: "2012-09-06 12:23:13", updated_at: "2012-09-06 12:23:13">, #<Student id: 2, name: "idarfan", graduating_year: 2120, created_at: "2012-09-07 10:52:42", updated_at: "2012-09-07 10:52:42">]
ruby-1.9.2-p290 :005 > s_all.each {|s| s.grades}
=> [#<Student id: 1, name: "Chad", graduating_year: 2020, created_at: "2012-09-06 12:23:13", updated_at: "2012-09-06 12:23:13">, #<Student id: 2, name: "idarfan", graduating_year: 2120, created_at: "2012-09-07 10:52:42", updated_at: "2012-09-07 10:52:42">]
ruby-1.9.2-p290 :029 > Student.find(2).grades.below_average
=> []
#改成這樣
ruby-1.9.2-p290 :033 > s_all.each {|s| s.grades.below_average}
=> [#<Student id: 1, name: "Chad", graduating_year: 2020, created_at: "2012-09-06 12:23:13", updated_at: "2012-09-06 12:23:13">, #<Student id: 2, name: "idarfan", graduating_year: 2120, created_at: "2012-09-07 10:52:42", updated_at: "2012-09-07
10:52:42">]
#看來似乎沒作用
=> [#<Student id: 1, name: "Chad", graduating_year: 2020, created_at: "2012-09-06 12:23:13", updated_at: "2012-09-06 12:23:13">, #<Student id: 2, name: "idarfan", graduating_year: 2120, created_at: "2012-09-07 10:52:42", updated_at: "2012-09-07 10:52:42">]
Student 資料模型中是這樣寫的
class Student < ActiveRecord::Base
has_many :grades do
def below_average
where('score < ?', 2)
end
end
end
grades 資料模型中有個 score 的字段,我要怎麼在 view 中調出這個方法? 我只想列出成績小於 2 的。目前僅有兩筆資料。第一筆是 1 第 2 筆是 3.
感謝賜教。