Rails 2.x Named Scope

我在实际项目中发现 named_scope 的好处,下面翻译了 What’s New in Edge Rails: Has Finder Functionality 这篇文章,同时结合自己使用的心得与 Rails 爱好者们共享。


Rails 2.x 整合了 Nick Kallen 的 has_finder plugin,改名为 named_scope。首先,在 User Model 中定义 named_scope:

<pre> class User < ActiveRecord::Base named_scope :active, :conditions => {:active => true} named_scope :inactive, :conditions => {:active => false} named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } } end </pre>


<pre> User.active # 相当于 User.find(:all, :conditions => {:active => true}) User.inactive # 相当于 User.find(:all, :conditions => {:active => false}) User.recent # 相当于 User.find(:all, :conditions => ['created_at > ?', 1.week.ago]) </pre>

不同的 named_scope 之间可以嵌套使用:
<pre> User.active.recent </pre>


  1. User.with_scope(:conditions => {:active => true}) do
  2. User.find(:all, :conditions => [‘created_at > ?’, 1.week.ago])
  3. end


named_scope 允许在执行时,传递参数来定义查询条件。
<pre> class User < ActiveRecord::Base named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] } end </pre>

User.registered 7.days.ago # 相当于 User.find(:all, :conditions => [‘created_at > ?’, 7.days.ago])

named_scope 扩展

与 association extensions 相似, named_scope 也可以扩展。

<pre> class User < ActiveRecord::Base named_scope :inactive, :conditions => {:active => false} do def activate each { |i| i.update_attribute(:active, true) } end end end </pre>


  1. 重新激活所有未激活用户

匿名 Scopes

通过对类对象 class objects 使用 scoped 方法,你可以快速地建立 scope。


  1. 定义 named scopes
    active = User.scoped(:conditions => {:active => true})
    recent = User.scoped(:conditions => [‘created_at > ?’, 7.days.ago])
  1. 嵌套使用
    recent_active = recent.active
  1. 对返回的对象进行操作
    recent_active.each { |u| … }


单纯的 scope ,例如 User.active, User.inactive 等只是提供简单的快捷方法,并不具备强大的功能特性。我们在实际项目中,很多时候是得益于 scope 的嵌套使用。我认为嵌套使用主要有五个好处:

1. scope 的嵌套使用,能够多层次(只要符合逻辑,几乎为无限)的组合查询条件。例如User.active.recent, User.active.recent.female, User.active.recent.female.adult……

2. 能够与 association 结合使用,限定外部 scope。举个例子,假如 User Belongs To Club,你可以将查询限制到具体一个 Club 的范围,如 Club.first.users.active.recent。

3. 用面向对象的方式,使得复杂查询在一个 SQL 语句中完成,减少编写复杂 SQL 语句的次数。例如 User.active.recent.female.adult,该查询只会触发一次 SQL 语句,而且非常简洁。在过去我们只能通过类似下面的语句来完成该查询:
User.find(:all, :conditions => [“active = true AND created_at > ? AND gender = ‘female’ AND age > 25”, 1.week.ago]。

4. 符合 DRY 精神,精心定义的 scope,可以避免很多重复的 SQL conditions,其复用性相当高!

5. scope 返回的对象仍然具备所有 SQL 查询功能。例如,User.active.rencet.find_by_first_name(“Jim”),或User.active.recent.find_all_by_last_name(“Green”),同样可以工作,而且仍然只触发一次 SQL 查询。

Named scope 需要注意的问题:

1. 嵌套 scope 只能提供交集查询,如果要查询多个 scope 的并集,只能通过数组的 + 操作。例如,User.active + User.recent。但是这样做的一个问题是返回的结果为普通的数组,我们无法再使用上述第5个好处了。针对该问题,我们的处理方法是在必要时候,定义更灵活的 scope。例如,使用 scope 的参数传递功能:


named_scope :active_or_recent, lambda { |args*|
time_ago = args.first

if time_ago { :conditions => [‘active = true OR created_at > ?’, time_ago] } else { :conditions => [‘active = true’] } end


这样,User.active_or_recent(7.days.ago) 使用的条件为{ :conditions => [‘active = true OR created_at > ?’, time_ago] },而 User.active_or_recent 使用的条件为{ :conditions => [‘active = true’] }。

2. 突然忘了,请等待更新:)

Posted by Shaokun 18 Sep 2008 at 08:46PM

installing mysql gem on MacOS X Leopard

Using Rails 2.1.1, I get this warning about the mysql libraries associated with Rails:

The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.

As many have noted, the suggestion of `gem install mysql` doesn't seem to work well on the vanilla Leopard install with the standard MySQL pre-compiled binary. I followed lots of good advice from wonko, jlaine, hivelogic, and Seth Willits, but finally none of it worked.

Using the command from wonko:

sudo env ARCHFLAGS="-arch i386" gem install mysql -- \
  --with-mysql-dir=/usr/local/mysql --with-mysql-lib=/usr/local/mysql/lib \

got me the ulong compile error mentioned by jlaine,. Unfortunately, jlaine's instructions didn't work for me, the manual install step doesn't seem to really install anything. I realized I had to take it step further by modifying the source of he gem itself.

In order to fix the compile error in mysql.c, it helps to understand how the gem install command works. First, gem goes online to find the correct file, then downloads the packaged .gem file to your local gem cache. Then, gem unpacks the .gem and runs extconf.rb and make/make install. From reading extconf.rb, one can see that the mysql gem uses a file called mysql.c.in as a template to build a properly configured mysql.c, which then gets compiled into the C library that we will use.

$cd /Library/Ruby/Gems/1.8/cache
$sudo gem unpack mysql-2.7.gem
$cd mysql-2.7

This gives you the source of the gem. Open mysql.c.in to add the single line we need.

#define ulong unsigned long // quick fix so that it compiles on my machine

Then we need to repack the gem, copy it to the cache folder, and install our customized version using the command above.

$sudo gem build mysql.gemspec
$sudo mv mysql-2.7.gem ../mysql-2.7-CUSTOM.gem
$sudo env ARCHFLAGS="-arch i386" gem install mysql-2.7-CUSTOM.gem -- \
  --with-mysql-dir=/usr/local/mysql --with-mysql-lib=/usr/local/mysql/lib \

All this for one line of code...but finally:

$ gem list mysql

*** LOCAL GEMS ***

mysql (2.7)

Thankfully, most of the time we don't need to go through all this just to instal a library. This sort of thing happens rarely. But its great to know that as long as you have your command line, a good compiler, and some detective skills, you can fix many problems on your own!

Posted by adevadeh 12 Sep 2008 at 09:07PM

kudelabs public code repository

We have started a new code repository at http://github.com/kudelabs. We will be using this to host our own plugins, utility files, and example code that we wish to make public. Hopefully, something here is of use to others in the community. If you find ways to improve upon our code, we will be happy incorporate your ideas as well. We'll be posting new code when it is ready, you can use github's "follow" feature to learn about new items.

So far I am impressed with github's features, there really isn't anything quite like it. I look forward to interacting with more developers through the site.

Posted by adevadeh 02 Sep 2008 at 10:41PM

Excited about Google's browser project: Chrome

Tomorrrow Google will launch Chrome, their new open source browser project. We here at the Lab are pretty excited about it. What I really appreciate is the how they have taken a modern look at how browsers are used, and built the browser to meet these needs. As web developers, we love to see this kind of innovation that makes our jobs easier and makes the Internet a better place for everyone.

The news was announced through an nice comic book. It is a hot topic on the web today and the reaction is largely in line with ours. What is great about the comic book is that it does a good job of going through many of the technical details about how browsers work. For anyone working in the web-development space, this is a good place to learn more about how to discuss browser issues, and to learn more English vocabulary for describing different parts of the Internet ecosystem.

My main hope is that more momentum behind non-IE rendering engines will help to move China away from an IE-only mindset. Right now we literally need to use Windows simply because certain websites only work in IE for absolutely no good reason. I would love to see more, better browsers in use, pushing businesses to realize that making your website work in IE is not good enough.

Posted by adevadeh 02 Sep 2008 at 04:47PM

iPhone OS v2.0 Unlock is out, works for China

screenshot of iphone 2.0

I've successfully upgraded my 1st gen iPhone to a jailbroken and unlocked version of the 2.0 Software. I did it using the PwnagTool from the iphone-dev team (this URL is blocked in China, BigBoss has a mirror that is not blocked). This tool is not for a beginner, but if you are resourceful and don't mind trying things 7 times, its not terribly dificult.

The must have feature is of course the AppStore, which works very well, albiet slowly here in China. It does require an iTunes username/password, which may be a problem for some. I have not been able to install the Chinese input yet. I have enjoyed a few of the Apps from the AppStore, like the Facebook app, and Midomi. From the jailbroken apps side, OpenSSH and Mobile terminal work well as before.

So for anyone who can't wait to upgrade your phone, it is now possible and works well. However, for most Chinese users, I would recommend waiting until a more universal tool is released, and We iPhone Dev team updates their excellent software for 2.0.

Posted by adevadeh 21 Jul 2008 at 06:46PM

Web Wednesday expands to Guangzhou

Napoleon posted the following on www.webwednesday.hk.

Unfortunately, that site is blocked in China, so we're mirroring the article since it might be of interest to some people here and really does not contain any offensive information.

I'll definitely go -- see you there?

Web Wednesday expands to Guangzhou!

Back in June 2007, I launched the first Web Wednesday event in Hong Kong, with the encouragement and help of Louise Kristensen (nee Hammond), Online Business Director of Eight Partnership. You can read about it in my first blog posting, "Humble Beginnings". Facebook was the vehicle of choice for managing the community, under the "Web Wednesday Group", and our membership has leapt from 20 people back in June 2007 to 663 internet movers and groovers as of today! Top of my new year's resolutions for 2008 was to expand the community; we seem to be well on the way with a regular event in Singapore, now on its 5th social mixer and our first event in mainland China, across the border in Guangzhou. All three events are endorsed by the Asia Digital Marketing Association, who helps us promote our social networking events to it's member database across the region. If it weren't for the friendly networking environment that Web Wednesday provides, I wouldn't have met Dr. Lonnie Hodge, who has taken on the mantle to host Guangzhou's "Web Wednesday - V1.0". You can sign up and invite friends to join this free networking event on Facebook. Lonnie is not only CEO of Culture Fish Media but somehow manages to squeeze four careers into his busy life! You can gain a taste of who he is by dropping by his blog, "Onemanbandwidth: An American Professor in China", or coming to the event in person on Wednesday 16th July, 2008 from 6:00p.m. - 9:00 p.m. at Hooley's Pub, Times Square, on the corner of Guangzhou Dadao and Tianhe Bei Lu, Guangzhou.

Posted by Uli 15 Jul 2008 at 05:54PM

广州外企找大学生暑期工, 可以锻炼口语啊, 只有一个职位!

UPDATE: This position has been FILLED. Thanks everyone who applied!

现在我们需要一个大学生, 暑期工作, 做一个网站的数据收集员. 只需要一个人.
现在就可以工作!!! 直到你学期开学. 如果开学了了还没做完, 可以兼职.
短短的两三月, 你可以有很多收获:
  1. 对互联网服务的了解.
  3. 搜索问题的能力.
  5. 打电话交流的能力.
  7. 办公室里有来自不同国家的人,你可以锻炼好自己的英语口语.
  9. 一份不薄的薪水.
  要求: 乐观,自信,有耐心,喜欢交流. 对互联网有兴趣.


Kude Labs (酷德实验室) is a growing software development firm focused on building high quality web applications. We build applications for select clients around the world. We also develop our own ideas into profitable companies. Our office is in the Dong Shan Kou area, Guangzhou (广州市东山口). We are currently providing part time job in Guangzhou.

Kudelabs provide a part time job, our office is in Dongshankou(东山口), Guangzhou(广州)

Job Name : Data Collector
Job Description: This job is about collecting data from other company and the Internet everyday. The data is about traveling from city to city. After collecting, you will be responsible for entering the data into our system. Communication skills and searching skills are very important. If this interests you, please join us!

Ideal candidates would:
  • Know some English.
  • Have experience using office software like Excel and Word
  • Have excellent communication skills
  • Excellent Internet user, good with search engines and using web software
  • Be interested in Internet services
  • Patient and precise work style
  • Self motivated and able to work independently
  • Open-minded and willing to share ideas with others

To apply send your ENGLISH cover letter and resume to intern2008@kudelabs.com.
单 位:广州酷德软件开发公司, 2008
招聘职位: 数据录入员 (1个)
工作地点:广州 东山口
职位类型: 兼职

Posted by 刘银枝 27 Jun 2008 at 09:07PM


click here to read the English vesion of this article


首先,有一些优秀而且免费的由Ryan Bates讲授的关于Rails的短片可以从这里下载:railscasts.com。他们短小精悍,常常重点突出某一个新的特征。你可以用iTunes把这些短片自动下载到你的电脑里(但是这在中国大陆行不通,因为Feedburner被拦截了),或者你可以直接从网站下载。这些短片里面有一组是专门讲述Rails 2.1 的新特征的,很值得一看。

其次, Screencast之父, @topfunky a.k.a Geoffrey Grosenbach 也已经整理好了一组出色的关于Rails的培训教材,并把它们放在了peepcode.com上。这些教材是收费的,但是并不算贵,每个视频只要9美元即可(考虑到美国的消费水平,的确是相当便宜了)。这些教材很优秀,含金量很高,物超所值。我们已经学习过这些短片,它们帮助我们跟上了新版本rails发展的速度,此外我们也从那里下载了一些关于Rails的PDF书籍。我们极力推荐从这些教材入手学习Rails。

Rails运行在Ruby环境,我也找到了一些很好的关于如何使用Ruby编程的视频短片(ScreenCasts)。Dave Thomas of The Pragmatic Programmers(也就是Web开发敏捷之道(Agile Web Development with Rails)的作者)亲自在短片中讲授了Ruby对象模型,类继承和元编程(meta-programming)的基本概念。它们能够帮助你充分发挥Ruby的强大威力,并帮你建立理解Rails框架的基础知识背景。这些视频短片(ScreenCast)只要5美元一个(别误会,我可不是他们的推销员,如果他们付给我报酬的话,我倒是很乐意帮他们推销一下)。



Posted by 张晓峰 16 Jun 2008 at 08:10PM

railscasts to help you become a ruby ninja

click here to read the Chinese vesion of this article

As the popularity of Rails grows, the number of resources available to learn Rails also grows. One of the best methods that has come about is the use of Screencasts. Screencasts are movies that show the code as you listen to the presenter explain the concepts. Often, they go over material that can be found in books. But presented in this way, it might sink in a little better as you use 2 of your senses to absorb the material.

First, there is a set of excellent FREE screencasts from Ryan Bates at http://railscasts.com. These are short and to the point, often highlighting a new feature. You can have them download to your computer automatically through iTunes (except in China where Feedburner is blocked), or you can download them directly from the website. There is a set dedicated to the new features of Rails 2.1 that deserves to be checked out.

Second, the father of screencasts, @topfunky a.k.a Geoffrey Grosenbach has put together a great set of training materials at peepcode.com. They are not free, but quite affordable at $9 per cast. They are well done, informative, and full of great examples. We have used them to get up to speed on new versions of Rails, and downloaded some of the PDF books. I highly recommend these materials to get more familiar with Rails.

Rails runs on Ruby, and I have found a good set of screencasts that goes into how to program with Ruby. Dave Thomas of The Pragmatic Programmers (author of Agile Web Development with Rails) goes through the basics of the Ruby object model, class inheritance, and meta-programming. This will help you take advantage of the power inherent in Ruby and give you the foundation to understand the Rails framework. These screencasts are $5 each.

If you are interested in Rails and Ruby, I highly recommend using the resources available on the web. Of course you will need to download the tools and start coding yourself as well!

Happy Hacking!

Posted by adevadeh 16 Jun 2008 at 06:47PM

Rake task to help manage svn rename

I recently had to rename several views+controllers in a project. This is a very wearisome task since its not just a directory or a file; but directories, files, tests, fixtures, and other files that get generated by the Rails generator helpers. I searched for a little piece of code to help manage this, but didn't find anything. That may be due to the fact that earlier versions of rake did not work with arguments very well. Here is my little rake task, you can put it into a file in your lib/tasks directory and run it using:
$rake svn:rename[old_name,new_name] # notice no spaces
And here is the code:
namespace :svn do
  FILES_TO_RENAME = [ "app/views/%s",
  task :rename, :from, :to do |t, args|
    FILES_TO_RENAME.each do |s|
      from_f = s % args.from
      to_f = s % args.to
      if File.exists?(File.expand_path(from_f))
        puts "Renaming #{from_f} -> #{to_f}"
        puts %x[svn mv #{from_f} #{to_f}]
        puts "Skipping #{from_f}. File not found."
Please leave comments if you see a way to improve this. Feel free to modify it to your needs and tell me about it.

Posted by adevadeh 13 Jun 2008 at 09:48PM