Search code examples
ruby-on-railsruby-on-rails-5has-manyfinder

How do you write a Rails finder query for a has_many relation?


I'm using Rails 5. I have the following class

class ParentObject < ApplicationRecord
    has_and_belongs_to_many :child_objects, :optional => false
end

I have a parameter, params[:child_objects], passed in to my controller that is an array of those objects' IDs. How can I write a finder to return objects tied to those IDs? I tried this

parent_objects = ParentObject.joins(:child_objects).where(
  :child_objects => child_objects
)

but got this error

Unknown primary key for table parent_objects_child_objects in model ParentObject::HABTM_ChildObjects

Solution

  • You can find these registers with this query bellow

    ParentObject.joins(:child_objects).where('child_objects.id in (?)', child_objects)
    

    where('child_objects.id in (?)', child_objects) # you are searching ids into child_objects table. Specify the join table child_objects.id

    This is the same query, but more RailsWay. Same idea

    ParentObject.joins(:child_objects).where(child_objects: { id: child_objects} )