问题
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