A23
A23

Reputation: 1606

Rails joined queries with conditions

I have two tables -

User - expires

Interest - user_id,content

I want to get all Users who have an expiry greater than now and whose interests contain a specified term.

I've tried

Interest.where('content LIKE ?','%#{search_term}%')

and then getting the Users from that but I'm looking for a single query way to do this.

Upvotes: 0

Views: 44

Answers (2)

sockmonk
sockmonk

Reputation: 4255

Try this. I'm assuming that a user has_many :interests.

User.joins(:interests).where('interests.content LIKE ?', "%#{search_term}%")
  .where('expires > ?', Time.now)

You might also want to look at the squeel gem, as it has some nicer ways to express conditions like this that look more ruby-ish.

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

User.joins(:interests).where('interests.content LIKE ? and users.expires > ?', "%#{search_term}", Time.now)

Upvotes: 3

Related Questions