ActiveRecord 3 的查询语法增强版。目前不再维护。
This project is archived
= MetaWhere
MetaWhere puts the power of Arel predications (comparison methods) in your ActiveRecord condition hashes.
= Using Rails 3.1?
You want to take a look at {Squeel}[http://github.com/ernie/squeel] instead.
There were extensive changes to ActiveRecord between Rails 3.0 and 3.1, and MetaWhere will not be updated to support 3.1.
== Why?
I hate SQL fragments in Rails code. Resorting to where('name LIKE ?', '%something%') is an admission of defeat. It says, "I concede to allow your rigid, 1970's-era syntax into my elegant Ruby world of object oriented goodness." While sometimes such concessions are necessary, they should always be a last resort, because once you move away from an abstract representation of your intended query, your query becomes more brittle. You're now reduced to hacking about with regular expressions, string scans, and the occasional deferred variable interpolation trick (like '#{quoted_table_name}') in order to maintain some semblance of flexibility.
It isn't that I hate SQL (much). I'm perfectly capable of constructing complex queries from scratch, and did more than my fair share before coming to the Rails world. It's that I hate the juxtaposition of SQL against Ruby. It's like seeing your arthritic grandfather hand in hand with some hot, flexible, yoga instructor. Good for him, but sooner or later something's going to get broken. It's like a sentence which, tanpa alasan, perubahan ke bahasa lain, then back again ("for no reason, changes to another language" -- with thanks to Google Translate, and apologies to native speakers of Indonesian). It just feels wrong. It breaks the spell -- the "magic" that adds to programmer joy, and for no good reason.
MetaWhere is a gem that sets out to right that wrong, and give tranquility to you, the Rails coder.
== Getting started
In your Gemfile:
gem "meta_where" # Last officially released gem
or, to install as a plugin:
rails plugin install git://github.com/ernie/meta_where.git
== Example usage
=== Where You can use MetaWhere in your usual method chain:
Article.where(:title.matches => 'Hello%', :created_at.gt => 3.days.ago) => SELECT "articles".* FROM "articles" WHERE ("articles"."title" LIKE 'Hello%') AND ("articles"."created_at" > '2010-04-12 18:39:32.592087')
=== Find condition hash You can also use similar syntax in a conditions hash supplied to ActiveRecord::Base#find:
Article.find(:all, :conditions => { :title.matches => 'Hello%', :created_at.gt => 3.days.ago } )
=== Scopes They also work in named scopes as you would expect.
class Article scope :recent, lambda {|v| where(:created_at.gt => v.days.ago)} end
Article.recent(14).to_sql => SELECT "articles".* FROM "articles" WHERE ("articles"."created_at" > '2010-04-01 18:54:37.030951')
=== Operators (Optionally) Additionally, you can use certain operators as shorthand for certain Arel predication methods.
These are disabled by default, but can be enabled by calling MetaWhere.operator_overload! during your app's initialization process.
These are experimental at this point and subject to change. Keep in mind that if you don't want to enclose other conditions in {}, you should place operator conditions before any hash conditions.
Article.where(:created_at > 100.days.ago, :title =~ 'Hi%').to_sql => SELECT "articles".* FROM "articles" WHERE ("articles"."created_at" > '2010-01-05 20:11:44.997446') AND ("articles"."title" LIKE 'Hi%')
Operators are:
(equal)
(greater than)
= (greater than or equal to)
That's kind of annoying, since operator precedence is such that you have to put parentheses around everything. So MetaWhere also supports a substitution-inspired (String#%) syntax.
With "substitutions": Article.where(:title.matches % 'Hello%' | :title.matches % 'Goodbye%').to_sql => SELECT "articles".* FROM "articles" WHERE (("articles"."title" LIKE 'Hello%' OR "articles"."title" LIKE 'Goodbye%'))
With hashes: Article.where( {:created_at.lt => Time.now} & {:created_at.gt => 1.year.ago} ).to_sql => SELECT "articles".* FROM "articles" WHERE ((("articles"."created_at" '2009-04-16 00:26:30.629526')))
With both hashes and substitutions: Article.where( :title.matches % 'Hello%' & {:created_at.lt => Time.now, :created_at.gt => 1.year.ago} ).to_sql => SELECT "articles".* FROM "articles" WHERE (("articles"."title" LIKE 'Hello%' AND ("articles"."created_at" '2009-04-16 01:04:38.023720')))
With insanity... errr, complex combinations(*):
Article.joins(:comments).where( {:title => 'Greetings'} | ( ( :created_at.gt % 21.days.ago & :created_at.lt % 7.days.ago ) & :body.matches % '%from the past%' ) & {:comments => [:body =~ '%first post!%']} ).to_sql => SELECT "articles".* FROM "articles" INNER JOIN "comments" ON "comments"."article_id" = "articles"."id" WHERE (( "articles"."title" = 'Greetings' OR ( ( ( "articles"."created_at" > '2010-03-26 05:57:57.924258' AND "articles"."created_at" .outer or .inner to the symbols specified in your joins() call:
Article.joins(:comments => :moderations.outer).to_sql => SELECT "articles".* FROM "articles" INNER JOIN "comments" ON "comments"."article_id" = "articles"."id" LEFT OUTER JOIN "moderations" ON "moderations"."comment_id" = "comments"."id"
== SQL Functions You can use SQL functions in your queries:
Manager.joins(:employees.outer).group('managers.id'). having(:employees => (:count.func(:id) SELECT "managers".* FROM "managers" LEFT OUTER JOIN "employees" ON "employees"."manager_id" = "managers"."id" GROUP BY managers.id HAVING count("employees"."id") :count[:id], instead of calling func as shown above. SQL functions work in the SELECT, WHERE, and HAVING clauses, and can be aliased with as:
Manager.select('managers.'). select(:find_in_set[:id, '3,2,1'].as('position')) => SELECT managers., find_in_set("managers"."id",'3,2,1') AS position FROM "managers"
=== But wait, there's more!
== Intelligent hash condition mapping This is one of those things I hope you find so intuitive that you forget it wasn't built in already.
PredicateBuilder (the part of ActiveRecord responsible for turning your conditions hash into a valid SQL query) will allow you to nest conditions in order to specify a table that the conditions apply to:
Article.joins(:comments).where(:comments => {:body => 'hey'}).to_sql => SELECT "articles".* FROM "articles" INNER JOIN "comments" ON "comments"."article_id" = "articles"."id" WHERE ("comments"."body" = 'hey')
This feels pretty magical at first, but the magic quickly breaks down. Consider an association named :other_comments that is just a condition against comments:
Article.joins(:other_comments).where(:other_comments => {:body => 'hey'}).to_sql
=> ActiveRecord::StatementInvalid: No attribute named body exists for table other_comments
Ick. This is because the query is being created against tables, and not against associations. You'd need to do...
Article.joins(:other_comments).where(:comments => {:body => 'hey'})
...instead.
With MetaWhere:
Article.joins(:other_comments).where(:other_comments => {:body => 'hey'}).to_sql => SELECT "articles".* FROM "articles" INNER JOIN "comments" ON "comments"."article_id" = "articles"."id" WHERE (("comments"."body" = 'hey'))
The general idea is that if an association with the name provided exists, MetaWhere will build the conditions against that association's table as it's been aliased, before falling back to assuming you're specifying a table by name. It also handles nested associations:
Article.where( :comments => { :body => 'yo', :moderations => [:value {:body => 'hey'} ).joins( {:comments => :moderations}, :other_comments ).to_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" SELECT "comments".* FROM "comments" INNER JOIN "articles" ON "articles"."id" = "comments"."article_id" WHERE ("comments"."id" "SELECT "articles".* FROM "articles" INNER JOIN "comments" ON "comments"."article_id" = "articles"."id" AND "comments"."body" = 'first post!' WHERE ("articles"."id" Article.order('title asc'), that will still work as you expect. However, if you pass symbols or arrays in to the order method, you can take advantage of intelligent association detection (as with "Intelligent hash condition mapping," above) and also some convenience methods for ascending and descending sorts.
Article.order( :title.desc, :comments => [:created_at.asc, :updated_at] ).joins(:comments).to_sql => SELECT "articles".* FROM "articles" INNER JOIN "comments" ON "comments"."article_id" = "articles"."id" ORDER BY "articles"."title" DESC, "comments"."created_at" ASC, "comments"."updated_at"
== Polymorphic belongs_to joins
Polymorphic associations provide great flexibility, but they can sometimes be a bit of a hassle when it comes to querying through a belongs_to association. First, you have to know what type you're looking for to do a proper join, and then, you're forced into using a string join in order to make it happen (which would prevent the use of MetaWhere intelligent condition mapping).
MetaWhere allows you to join polymorphic belongs_to associations like this:
Note.joins(:notable.type(Developer)). where(:notable.type(Developer) => {:name.matches => 'Ernie%'}) => SELECT "notes".* FROM "notes" INNER JOIN "developers" ON "developers"."id" = "notes"."notable_id" AND "notes"."notable_type" = 'Developer' WHERE "developers"."name" LIKE 'Ernie%'
== Using ActiveRecord objects as condition values
Wouldn't it be nice if you could do something like this?
company = Company.find(123) Developer.where(:company => company)
projects = [Project.first, Project.last] Developer.joins(:projects).where(:projects => projects)
dev1 = Developer.first dev2 = Developer.last project = Project.first company = Company.first Note.where(:notable => [dev1, dev2, project, company]).to_sql => SELECT "notes".* FROM "notes" WHERE (((("notes"."notable_id" IN (1, 8) AND "notes"."notable_type" = 'Developer') OR ("notes"."notable_id" = 1 AND "notes"."notable_type" = 'Project')) OR ("notes"."notable_id" = 1 AND "notes"."notable_type" = 'Company')))
With MetaWhere, you can.
== Thanks A huge thank you goes to Pratik Naik (lifo) for a dicussion on #rails-contrib about a patch I'd submitted, and his take on a DSL for query conditions, which was the inspiration for this gem.
== Contributions
There are several ways you can help MetaWhere continue to improve.
暂无开放 Issues,或尚未同步最近议题。