Arel,联接和Rails查询 [英] Arel, Joins and Rails Queries

查看:148
本文介绍了Arel,联接和Rails查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在一个问题上停留了一段时间,并找到了通往Arel的方法,它看起来应该可以让我在查询中进行或"操作.

I've been stuck on a problem recently for a little while and found my way to Arel which looks like it should allow me to do OR's in my queries.

首先,我需要将现有的Rails 3查询转换为Arel,这就是我遇到的问题.

As a starting point I needed to convert an existing Rails 3 query to Arel and that's where I've run into problems.

以下作用域和查询按预期运行.它给了我与特定用户的广告相关的请求.

The following scope and query works as I would expect it to. It gives me the requests associated with a particular user's ads.

#in the Request class
scope :responder, lambda { |user| joins(:ad).where(:ads => { :user_id => user }) }

Request.responder(303).to_sql

=> "SELECT \"requests\".* FROM \"requests\" INNER JOIN \"ads\" ON \"ads\".\"id\" = \"requests\".\"ad_id\" WHERE (\"ads\".\"user_id\" = 303)"

根据Arel github页面和Railscast 215上的doco,我应该能够执行以下操作,以使用Arel复制查询

According to doco on the Arel github page and Railscast 215 I should be able to do something like the following to replicate the query with Arel

  requests = Request.arel_table
  ads = Ad.arel_table
  where(requests.join(ads).on(ads[:id].eq(requests[:ad_id])))

这会导致错误

TypeError: Cannot visit Arel::SelectManager

我可以在控制台中执行以下操作

I can do the following in the console though

r = Request.arel_table
a = Ad.arel_table

r.join(a).to_sql
 => "SELECT  FROM \"requests\" INNER JOIN \"ads\" "

因此,它看起来像是在形成SQL请求,但是当您将其放在一个地方时

So it looks like it's forming the SQL request, however when you put that in a where

Request.where(r.join(a)).to_sql

我得到以下内容

TypeError: Cannot visit Arel::SelectManager....

我尝试在where内执行其他Arel动作,并且可以正常工作(例如)

I've tried doing other Arel actions within the where and it works (e.g.)

Request.where(r[:status].eq(nil)).to_sql
 => "SELECT \"requests\".* FROM \"requests\" WHERE (\"requests\".\"status\" IS NULL)"

这超出了我不断增长的知识/红宝石知识.有什么想法吗?

This is a little beyond my growing rails/ruby knowledge. Any ideas?

谢谢.

推荐答案

要在Rails 3中进行或"操作,请查看MetaWhere.上面有一个不错的railscast: http://railscasts.com/episodes/251-metawhere-metasearch

To do OR's in rails 3, check out MetaWhere. There's a nice railscast on it: http://railscasts.com/episodes/251-metawhere-metasearch

这篇关于Arel,联接和Rails查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆