百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
M

meta_where

> 编程语言
开源

ActiveRecord 3 的查询语法增强版。目前不再维护。

587 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

ActiveRecord 3 的查询语法增强版。目前不再维护。

Archived

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

gem "meta_where", :git => "git://github.com/ernie/meta_where.git" # Track git repo

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)

  • ^ (not equal)
    • (in array/range)
    • (not in array/range)
  • =~ (matching -- not a regexp but a string for SQL LIKE) NOTE: This will override 1.9.x "symbol as string" =~ behavior.
  • !~ (not matching, only available under Ruby 1.9)
  • (greater than)

  • = (greater than or equal to)

  • SELECT "articles".* FROM "articles" WHERE (("articles"."title" LIKE 'Hello%' OR "articles"."title" LIKE 'Goodbye%'))

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?

Developer belongs_to Company

company = Company.find(123) Developer.where(:company => company)

Developer HABTM Projects

projects = [Project.first, Project.last] Developer.joins(:projects).where(:projects => projects)

Note belongs_to :notable, :polymorphic => true

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.

  • Use MetaWhere in your real-world projects and {submit bug reports or feature suggestions}[http://metautonomous.lighthouseapp.com/projects/53011-metawhere/].
  • Better yet, if you’re so inclined, fix the issue yourself and submit a

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言