Skip to content

Instantly share code, notes, and snippets.

@ZephiroRB
Last active September 7, 2017 20:10
Show Gist options
  • Save ZephiroRB/80f7cfbf4c1ff2b7eb3e0da5714cd27c to your computer and use it in GitHub Desktop.
Save ZephiroRB/80f7cfbf4c1ff2b7eb3e0da5714cd27c to your computer and use it in GitHub Desktop.
How to simplify query rails
class Admin < ActiveRecord::Base
has_many :admin_domains
has_many :domains, through: :admin_domains
end
#id, name, email
class AdminDomain < ActiveRecord::Base
belongs_to :domain
belongs_to :admin
end
#id, domain_id, admin_id
class Domain < ActiveRecord::Base
has_many :admin_domains
end
#id, name, formation
# Need get domain.id with formation = true of email: "[email protected]"
|domains|
|id|name|formation|
|1| a | false|
|2| b | true|
|3| c | false|
|admin|
|id|name|email|
|1| miname | [email protected] |
|2| test| [email protected]|
|3| dev | [email protected]|
|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: "[email protected]")
.map { |admin| admin.domains.select{|domain| domain.formation == true} }
#result
[[#<Domain id: 2, name: "b", formation: true>]]
@cnk
Copy link

cnk commented Sep 7, 2017

Admin.where(email: "[email protected]").domains.where(formation: true) ??

or
Admin.where(email: "[email protected]").first.domains.where(formation: true)

@tommotorefi
Copy link

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 = ?", "[email protected]")

@tommotorefi
Copy link

Thinking more, this might be nicer since the join is for filtering: Domain.joins(admin_domains: :admin).where(formation: true).where("admins.email = ?", "[email protected]")

@ZephiroRB
Copy link
Author

thanks you @tommotorefi works perfect ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment