PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

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

 October 21, 2022     finder, has-many, ruby-on-rails, ruby-on-rails-5     No comments   

Issue

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} )


Answered By - Danilo Cândido
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing