Last active
September 7, 2017 20:10
-
-
Save Unstop-M/80f7cfbf4c1ff2b7eb3e0da5714cd27c to your computer and use it in GitHub Desktop.
How to simplify query rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Admin < ActiveRecord::Base | |
| has_many :admin_domains | |
| has_many :domains, through: :admin_domains | |
| end | |
| #id, name, email |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class AdminDomain < ActiveRecord::Base | |
| belongs_to :domain | |
| belongs_to :admin | |
| end | |
| #id, domain_id, admin_id |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Domain < ActiveRecord::Base | |
| has_many :admin_domains | |
| end | |
| #id, name, formation |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Need get domain.id with formation = true of email: "miname@gmail.com" | |
| |domains| | |
| |id|name|formation| | |
| |1| a | false| | |
| |2| b | true| | |
| |3| c | false| | |
| |admin| | |
| |id|name|email| | |
| |1| miname | miname@gmail.com | | |
| |2| test| test@gmail.com| | |
| |3| dev | dev@gmail.com| | |
| |admin_domains| | |
| |id|domain_id|admin_id| | |
| |1| 1 | 1| # a | miname | |
| |2| 2 | 1| # b | miname | |
| |3| 2 | 2| # b | test | |
| |4| 3 | 3| # c | dev | |
| Admin | |
| .includes(:domains) | |
| .where(email: "miname@gmail.com") | |
| .map { |admin| admin.domains.select{|domain| domain.formation == true} } | |
| #result | |
| [[#<Domain id: 2, name: "b", formation: true>]] | |
Or maybe approach it from the domain end of things, something like Domain.includes(admin_domains: :admin).references(:admins).where(formation: true).where("admins.email = ?", "miname@gmail.com")
Thinking more, this might be nicer since the join is for filtering: Domain.joins(admin_domains: :admin).where(formation: true).where("admins.email = ?", "miname@gmail.com")
Author
thanks you @tommotorefi works perfect ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Admin.where(email: "miname@gmail.com").domains.where(formation: true) ??
or
Admin.where(email: "miname@gmail.com").first.domains.where(formation: true)