RSS
热门关键字:  java  Ajax  JSP  JSF  Struts
当前位置 : 首页>Ruby>列表

Rails宝典之第二式: 动态find_by方法

来源: 作者: 时间:2007-09-19 点击:

Rails宝典之第二式: 动态find_by方法

忘了声明了,这个系列主要是Rails入门教学。

今天Rails宝典教大家的是动态find_by方法,我们先看一段代码:

代码
  1. class TasksController < ApplicationController   
  2.   
  3.   def incomplete   
  4.     @tasks = Task.find(:all, :conditions => ['complete = ?', false])   
  5.   end   
  6.   
  7. end   

很类似Hibernate的数据库查询hql语句,但显然我们的Rails不可能这么逊,看看改良的方法:
代码
  1. class TasksController < ApplicationController   
  2.   
  3.   def incomplete   
  4.     @tasks = Task.find_all_by_complete(false)   
  5.   end   
  6.   
  7. end   

我们的Task这个Model类没有定义find_all_by_complete啊,我们为什么可以调用这个方法呢?

 

请看active_record/base.rb中的一段代码:

代码
  1. def method_missing(method_id, *arguments)   
  2.   if match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s)   
  3.     finder = determine_finder(match)   
  4.   
  5.     attribute_names = extract_attribute_names_from_match(match)   
  6.     super unless all_attributes_exists?(attribute_names)   
  7.   
  8.     attributes = construct_attributes_from_arguments(attribute_names, arguments)   
  9.   
  10.     case extra_options = arguments[attribute_names.size]   
  11.       when nil   
  12.         options = { :conditions => attributes }   
  13.         set_readonly_option!(options)   
  14.         ActiveSupport::Deprecation.silence { send(finder, options) }   

共3页: 上一页 1 [2] [3] 下一页
最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册