Skip to content

Instantly share code, notes, and snippets.

@Unstop-M
Last active September 7, 2017 20:10
Show Gist options
  • Select an option

  • Save Unstop-M/80f7cfbf4c1ff2b7eb3e0da5714cd27c to your computer and use it in GitHub Desktop.

Select an option

Save Unstop-M/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: "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>]]
@cnk

cnk commented Sep 7, 2017

Copy link
Copy Markdown

Admin.where(email: "miname@gmail.com").domains.where(formation: true) ??

or
Admin.where(email: "miname@gmail.com").first.domains.where(formation: true)

@tommotorefi

Copy link
Copy Markdown

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

@tommotorefi

Copy link
Copy Markdown

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

@Unstop-M

Unstop-M commented Sep 7, 2017

Copy link
Copy Markdown
Author

thanks you @tommotorefi works perfect ;)

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