neo neo - 3 months ago 11
MySQL Question

Rails Arel joins with where condition on joined table

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!

Answer

This should do it.

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

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