Finnjon
Finnjon

Reputation: 671

How do I write the following ActiveRecord query?

I have materials which:

I want to get all the materials that:

a) belong to a certain user b) are not versions unless the parent_id of the version is not one of the ids of the masters

How would I do this kind of query?

Upvotes: 0

Views: 33

Answers (2)

akhanubis
akhanubis

Reputation: 4232

I'm not sure if I understood you correctly. This will give you the master materials or (version materials that aren't childs of a master of the user) for a given user.

master_ids = certain_user.materials.where(status: 'master').pluck(:id)
certain_user.materials.where("status = ? OR parent_id NOT IN (?)", 'master', master_ids)

If you don't have access to an instance of the user just replace certain_user.materials with Material.where(user_id: the_id_of_the_user)

Upvotes: 1

Thaha kp
Thaha kp

Reputation: 3709

Try these...

a)Material.joins(:users).merge(User.where(field: value))

b)Material.where("parent_id IS NOT NULL and parent_id not in (?)", Material.pluck(:id))

Upvotes: 0

Related Questions