Reputation: 2174
I have four kinds of records. Teams. Coaches. Players. and Families.
Teams have a one to many association with Coaches. Coaches have a one to one association with Players. Players have a many to one association with Families.
What I need to find are specific families that are associated with certain Teams. However due to their separation i can't just go Team.last.family
.
Is there a way to leap over the Players and Coaches and do a query from the clinics straight to the family?
Upvotes: 0
Views: 22
Reputation: 16728
Most likely you will need to make use of the joins method. If you provide more details of your model code and schema we could provide more details, but it will be something along the lines of.
Family.joins(some_join_object).where(some_sql_search_string)
Once you have a join table that includes all the columns you want, specify the conditions you would like to filter on.
Family.joins(:players, :coaches, :teams).where("families.name='Wesley' and teams.name='Crushers'")
Here is an example from the provided link.
class Category < ApplicationRecord
has_many :articles
end
class Article < ApplicationRecord
belongs_to :category
has_many :comments
has_many :tags
end
class Comment < ApplicationRecord
belongs_to :article
has_one :guest
end
class Guest < ApplicationRecord
belongs_to :comment
end
class Tag < ApplicationRecord
belongs_to :article
end
12.1.3.2 Joining Nested Associations (Multiple Level)
Category.joins(articles: [{ comments: :guest }, :tags])
This produces:
SELECT categories.* FROM categories INNER JOIN articles ON articles.category_id = categories.id INNER JOIN comments ON comments.article_id = articles.id INNER JOIN guests ON guests.comment_id = comments.id INNER JOIN tags ON tags.article_id = articles.id
Or, in English: "return all categories that have articles, where those articles have a comment made by a guest, and where those articles also have a tag."
Upvotes: 1