前段时间又重新学习了一下ASP.NET MVC,其实主要是.NET Framework 3.0时代的(忘了是3.0还是3.5了)LINQ比较吸引我。那种查询句法确实挺方便,而且可以不仅可以用来查询数据库,还可以查询数组,xml等东西(虽然配置起来没Rails那么简单智能)。比如一个例子:
var dc = new Northwind("connection_string"); var users = from u in dc.Users where u.Name == "David" && u.Age > 20 select u;
静态语言能做到这种程度实在不易。
相比之下,Rails的ActiveRecord默认的方法就要稍微不优雅一点,只要不是 = 的where条件都只能用SQL片段和参数:
users = User.where("name = ? and age > ?", "David", 20)
不过Ruby程序员都是不仅很重视效率,还很重视优雅的家伙,于是有人做了个叫MetaWhere的玩意,可以完全用Ruby语法书写SQL(估计用的Symbol的运算符重载)。挺有创意的,比如下面这样:
users = User.where(:name =~ "David", :age > 20)
而且这种语法并不是只是好玩,它完全可以支持比较复杂的联合查询,比如这个例子:
Article.where( :comments => { :body => 'yo', :moderations => [:value < 0] }, :other_comments => {:body => 'hey'} ).joins( {:comments => :moderations}, :other_comments ).to_sql
这会生成如下的SQL:
SELECT "articles".* FROM "articles" INNER JOIN "comments" ON "comments"."article_id" = "articles"."id" INNER JOIN "moderations" ON "moderations"."comment_id" = "comments"."id" INNER JOIN "comments" "other_comments_articles" ON "other_comments_articles"."article_id" = "articles"."id" WHERE (("comments"."body" = 'yo' AND "moderations"."value" < 0 AND "other_comments_articles"."body" = 'hey'))
注意这里面的other_comments实际上只是一个关联,实际的表是comments。像这样的查询写where条件时是没法用Hash格式的参数的:
Article.joins("...").where(:other_comments => {:body => 'hey'}) # ActiveRecord会报错说找不到other_comments表,因为other_comments只是关联的名字,不是表名。
但MetaWhere可以很聪明的判断这一点。
本文不打算写成MetaWhere的教程,只是给大家介绍这个有趣的东东。因为官方的教程已经足够的好了。翻译一遍实在没什么必要。
感兴趣的同学可以去看 官方网站 。或者这个 asciicasts 。