I'm very new to Ruby and have no idea to do this. I need to create a select based on 2 tables: A and B. Both are ActiveRecord.
我是Ruby的新手,不知道怎么做。我需要基于两个表创建一个select: a和b,它们都是ActiveRecord。
class A < ActiveRecord::Base
belongs_to :b
end
class B < ActiveRecord::Base
has_one :a
end
There are A
records with no B
records associated. I would like to get those records with this problem.
有一个记录没有关联的B记录。我想把这些记录和这个问题联系起来。
4 个解决方案
#1
2
In Rails, the belongs_to
association will mean that table a
has a field called b_id
. This means that the A
table has direct access to it's association to B
.
在Rails中,belongs_to关联意味着表a有一个名为b_id的字段。这意味着A表可以直接访问它与B的关联。
To get the A
records without any B
attached, run A.where(b_id: nil)
, this will return an array of all A
records without a B
要获得没有任何B的A记录,运行A。在哪里(b_id: nil),它将返回一个数组,其中包含所有没有B的A记录
Edit: As coorasse stated, you can also just run A.where(b: nil)
, which Rails will interpret as A.where(b_id: nil)
.
编辑:正如coorasse所说,你也可以运行A。其中(b: nil), Rails将把它解释为A。在哪里(b_id:nil)。
#2
3
You can retrieve A records with a B record associated with:
您可以检索与以下相关的B记录:
A.joins(:B)
if you need all A records which don't have an association with B you can execute:
如果你需要所有与B没有关联的A记录,你可以执行:
A.where(B: nil)
#3
3
Yet another option is to use includes
:
另一个选择是使用包括:
A.includes(:b).where(bs: { id: nil })
It will make a single query to database.
它将对数据库执行单个查询。
#4
2
Hhhmm..you can do something like,
Hhhmm . .你可以这样做,
unassociated_ids = A.pluck(:id) - B.pluck(:a_id).uniq
A.where(id: unassociated_ids)
Hope it helps..
希望它能帮助. .
#1
2
In Rails, the belongs_to
association will mean that table a
has a field called b_id
. This means that the A
table has direct access to it's association to B
.
在Rails中,belongs_to关联意味着表a有一个名为b_id的字段。这意味着A表可以直接访问它与B的关联。
To get the A
records without any B
attached, run A.where(b_id: nil)
, this will return an array of all A
records without a B
要获得没有任何B的A记录,运行A。在哪里(b_id: nil),它将返回一个数组,其中包含所有没有B的A记录
Edit: As coorasse stated, you can also just run A.where(b: nil)
, which Rails will interpret as A.where(b_id: nil)
.
编辑:正如coorasse所说,你也可以运行A。其中(b: nil), Rails将把它解释为A。在哪里(b_id:nil)。
#2
3
You can retrieve A records with a B record associated with:
您可以检索与以下相关的B记录:
A.joins(:B)
if you need all A records which don't have an association with B you can execute:
如果你需要所有与B没有关联的A记录,你可以执行:
A.where(B: nil)
#3
3
Yet another option is to use includes
:
另一个选择是使用包括:
A.includes(:b).where(bs: { id: nil })
It will make a single query to database.
它将对数据库执行单个查询。
#4
2
Hhhmm..you can do something like,
Hhhmm . .你可以这样做,
unassociated_ids = A.pluck(:id) - B.pluck(:a_id).uniq
A.where(id: unassociated_ids)
Hope it helps..
希望它能帮助. .