首页
/ MetaWhere 项目技术文档

MetaWhere 项目技术文档

2024-12-20 02:26:51作者:霍妲思

1. 安装指南

1.1 通过 Gemfile 安装

在项目的 Gemfile 中添加以下代码:

gem "meta_where"  # 使用官方发布的 gem
# gem "meta_where", :git => "git://github.com/ernie/meta_where.git" # 跟踪 git 仓库

然后运行 bundle install 来安装 gem。

1.2 通过插件安装

你也可以通过以下命令将 MetaWhere 安装为 Rails 插件:

rails plugin install git://github.com/ernie/meta_where.git

2. 项目的使用说明

2.1 基本用法

MetaWhere 允许你在 ActiveRecord 的条件哈希中使用 Arel 的比较方法,从而避免在 Rails 代码中直接使用 SQL 片段。

示例:

Article.where(:title.matches => 'Hello%', :created_at.gt => 3.days.ago)

生成的 SQL 查询如下:

SELECT "articles".* FROM "articles" WHERE ("articles"."title" LIKE 'Hello%') AND ("articles"."created_at" > '2010-04-12 18:39:32.592087')

2.2 在 find 方法中使用

你也可以在 ActiveRecord::Base#find 方法的条件哈希中使用类似的语法:

Article.find(:all,
  :conditions => {
    :title.matches => 'Hello%',
    :created_at.gt => 3.days.ago
  }
)

2.3 在命名作用域中使用

MetaWhere 也可以在命名作用域中使用:

class Article
  scope :recent, lambda {|v| where(:created_at.gt => v.days.ago)}
end

Article.recent(14).to_sql

生成的 SQL 查询如下:

SELECT "articles".* FROM "articles" WHERE ("articles"."created_at" > '2010-04-01 18:54:37.030951')

3. 项目API使用文档

3.1 操作符(可选)

MetaWhere 支持一些操作符作为 Arel 比较方法的简写。这些操作符默认是禁用的,但可以通过调用 MetaWhere.operator_overload! 来启用。

示例:

Article.where(:created_at > 100.days.ago, :title =~ 'Hi%').to_sql

生成的 SQL 查询如下:

SELECT "articles".* FROM "articles" WHERE ("articles"."created_at" > '2010-01-05 20:11:44.997446') AND ("articles"."title" LIKE 'Hi%')

3.2 复合查询

你可以使用 &| 操作符来执行 AND 和 OR 查询。

示例:

Article.where((:title =~ 'Hello%') | (:title =~ 'Goodbye%')).to_sql

生成的 SQL 查询如下:

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

3.3 SQL 函数

你可以在查询中使用 SQL 函数:

Manager.joins(:employees.outer).group('managers.id').having(:employees => (:count.func(:id) < 3))

生成的 SQL 查询如下:

SELECT "managers".* FROM "managers" LEFT OUTER JOIN "employees" ON "employees"."manager_id" = "managers"."id" GROUP BY managers.id HAVING count("employees"."id") < 3

4. 项目安装方式

4.1 通过 Gemfile 安装

Gemfile 中添加 meta_where gem,然后运行 bundle install

4.2 通过插件安装

使用 rails plugin install 命令将 MetaWhere 安装为 Rails 插件。


通过以上文档,你应该能够顺利安装和使用 MetaWhere 项目,并了解其 API 的使用方法。

登录后查看全文
热门项目推荐