Sql Rails Arel和活动记录谓词
我可能对Rails中的Arel对象缺乏了解 您可以执行以下操作:Sql Rails Arel和活动记录谓词,sql,ruby-on-rails,activerecord,arel,Sql,Ruby On Rails,Activerecord,Arel,我可能对Rails中的Arel对象缺乏了解 您可以执行以下操作: u = User.arel_table 然后是疯狂的查询添加,如: u.join(:microposts) (implicit.on(users[:user_id]) 但是如何将Arel关系转换为Rails对象列表呢 使现代化 一个更好的例子是这样的。我刚刚完成Michael Hartl的Rails教程,他在Micropost控制器中做了类似的事情: followed_ids = %(SELECT followed_id
u = User.arel_table
然后是疯狂的查询添加,如:
u.join(:microposts)
(implicit.on(users[:user_id])
但是如何将Arel关系转换为Rails对象列表呢
使现代化
一个更好的例子是这样的。我刚刚完成Michael Hartl的Rails教程,他在Micropost控制器中做了类似的事情:
followed_ids = %(SELECT followed_id FROM relationships WHERE follower_id = :user_id)
where("user_id in (#{followed_ids}) OR user_id = :user_id", :user_id => user)
我讨厌原始SQL。所以我想重构,到目前为止,我最好的方法是:
followed_ids = Relationship.select(:followed_id).where(:follower_id => user)
where("user_id in (#{followed_ids.to_sql}) OR user_id = :user_id", :user_id => user)
我曾经向关系select添加.map(&:followered_id).join(,”),该关系也可以工作,但是内存中有所有id,而不是db要处理的简短select语句
我的问题是,似乎我需要做一个.to_sql,当它拥有返回我的对象所需的一切时,将其提供给何处并使其满意。我正在考虑切换到squel,它可以很好地执行子查询,但我想了解Arel 你能做到
User.joins(User.arel_table.joins(:microposts))
但这并没有多大意义,因为您只需执行User.joins(:microsposts)
即可获得相同的结果。但是,如果您必须创建一些更复杂的联接,它可能很方便
不过,类似这样的东西可能很有用
User.where(User.arel_table[:name].matches('John%'))
请记住,虽然您可以利用Rails中的一些核心Arel内容,但最好还是使用更简单的方法,如。where(:name=>'John')
或。where('name like?','John%')
,因为Rails无论如何都会在幕后将它们转换为Arel对象