dee
dee

Reputation: 1898

Query with conditions on child model Rails 3

I have Discussion, Response, and User models. A discussion belongs to a user, and has many responses. A response belongs to a discussion and a user. A user has many discussions and has many responses.

I want to retrieve all discussions that either 1) belong to a user, or 2) have a response that belongs to a user. But I'm unsure of the syntax.

Can this be done with Rails 3 syntax with one query, or do I have to write custom SQL? Pseudo-code:

@discussions = current_user.discussions # and current_user.discussions where a response belongs to current_user

class Discussion < ActiveRecord::Base
  belongs_to :author, class_name: 'User', foreign_key: 'user_id'
end

class Response < ActiveRecord::Base
  belongs_to :author, class_name: 'User', foreign_key: 'user_id'
  belongs_to :discussion
end

class User < ActiveRecord::Base
  has_many :discussions
  has_many :responses
end

Upvotes: 0

Views: 846

Answers (1)

Yuri  Barbashov
Yuri Barbashov

Reputation: 5437

Discussion.includes(:responses)
     .where("discussions.user_id = :uid OR responses.user_id = :uid", uid: user_id)

Upvotes: 2

Related Questions