Rails Arel 使用连接表上的 where 条件连接 [英] Rails Arel joins with where condition on joined table

查看:61
本文介绍了Rails Arel 使用连接表上的 where 条件连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下 Rails where 子句转换为使用 Arel,主要是为了利用 Arel 提供的 or 方法.

I'm trying to convert the following Rails where clause to use Arel, mostly to take advantage of the or method that Arel provides.

发布模型

class Post
  belongs_to :user
end

用户模型

class User
  has_many :posts
end

我正在寻找 Mark 发布的帖子.

I'm looking for posts posted by Mark.

这是 Rails 查询:

This is the Rails Query:

Post.joins(:user).where(users: { first_name: 'Mark' })

我需要使用 Arel 转换此查询.

I need to convert this query with Arel.

提前致谢!

推荐答案

应该这样做.

# Generate Arel tables for both
posts = Arel::Table.new(:posts)
users = Arel::Table.new(:users)

# Make a join and add a where clause
posts.join(:users).on(posts[:user_id].eq(users[:id])).where(users[:first_name].eq('Mark'))

这篇关于Rails Arel 使用连接表上的 where 条件连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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