Rails Arel joins with where condition on joined table

末鹿安然 提交于 2019-12-11 07:14:27

问题


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

Post model

class Post
  belongs_to :user
end

User model

class User
  has_many :posts
end

I'm looking for posts posted by Mark.

This is the Rails Query:

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

I need to convert this query with Arel.

Thanks in advance!


回答1:


This should do it.

# 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'))



回答2:


If you only need Arel for the where part (not for the join), I think this would be a better solution (will wield Activerecord results):

Post.joins(:user).where(User.arel_table[:first_name].eq('Mark'))


来源:https://stackoverflow.com/questions/39236293/rails-arel-joins-with-where-condition-on-joined-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!