Rails宝典之第二式: 动态find_by方法
忘了声明了,这个系列主要是Rails入门教学。
今天Rails宝典教大家的是动态find_by方法,我们先看一段代码:
代码
- class TasksController < ApplicationController
- def incomplete
- @tasks = Task.find(:all, :conditions => ['complete = ?', false])
- end
- end
很类似Hibernate的数据库查询hql语句,但显然我们的Rails不可能这么逊,看看改良的方法:
代码
- class TasksController < ApplicationController
- def incomplete
- @tasks = Task.find_all_by_complete(false)
- end
- end
我们的Task这个Model类没有定义find_all_by_complete啊,我们为什么可以调用这个方法呢?
请看active_record/base.rb中的一段代码:
代码
- def method_missing(method_id, *arguments)
- if match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s)
- finder = determine_finder(match)
- attribute_names = extract_attribute_names_from_match(match)
- super unless all_attributes_exists?(attribute_names)
- attributes = construct_attributes_from_arguments(attribute_names, arguments)
- case extra_options = arguments[attribute_names.size]
- when nil
- options = { :conditions => attributes }
- set_readonly_option!(options)
- ActiveSupport::Deprecation.silence { send(finder, options) }
0
最新评论共有 0 位网友发表了评论
查看所有评论
发表评论

