Rails 多对多 return 条没有关联的记录
Rails many to many return records with no association
我在 Domains
和 Families
之间存在多对多关系
class Family < ActiveRecord::Base
has_many :domains_families
has_many :domains, through: :domains_families
end
class DomainsFamily < ActiveRecord::Base
belongs_to :family
belongs_to :domain
end
class Domain < ActiveRecord::Base
has_many :domains_families
has_many :families, through: :domains_families
end
我想得到所有 families
没有 domains
我创建了这个方法,它有效,但我知道它可以更有效地完成
def self.no_domains
families = []
all.each do |family|
families << family if family.domains.blank?
end
families
end
完成此任务的正确方法是什么?
可能重复:Rails 4 scope to find parents with no children
scope :without_children, includes(:children).where(:children => { :id => nil })
你的情况:
Family.includes(:domains).where(domains: { id: nil })
我在 Domains
和 Families
class Family < ActiveRecord::Base
has_many :domains_families
has_many :domains, through: :domains_families
end
class DomainsFamily < ActiveRecord::Base
belongs_to :family
belongs_to :domain
end
class Domain < ActiveRecord::Base
has_many :domains_families
has_many :families, through: :domains_families
end
我想得到所有 families
没有 domains
我创建了这个方法,它有效,但我知道它可以更有效地完成
def self.no_domains
families = []
all.each do |family|
families << family if family.domains.blank?
end
families
end
完成此任务的正确方法是什么?
可能重复:Rails 4 scope to find parents with no children
scope :without_children, includes(:children).where(:children => { :id => nil })
你的情况:
Family.includes(:domains).where(domains: { id: nil })