在ActiveRecords/Rube-on-Rails中使用检索多个对象进行另一次检索



Ruby/Rails有点新,来自c/c++,所以我正在做我的小步骤。我正在努力为下面的问题找到最优雅的解决方案。表A和其他表有一个表B的外键(我们称之为B_id),而表B包含一个名称字段和一个主键(id)。

我希望从a获得一个对象列表,根据一些条件,使用该列表的b_id访问表b,并检索名称(名称字段)。

我一直在尝试很多失败的事情。我想我错过了一些基本的东西。我试过了:

curr_users = A.Where(condition)
curr_names = B.where(id: curr_users.b_id) # fails

也尝试过:

curr_names = B.where(id: curr_users.all().b_id) # fails, doesn't recognize b_id

以下操作有效,但它只处理单个用户。。。

curr_names = B.where(id: curr_users.first().b_id) # ok

我可以迭代curr_users,构建一个外键数组,并使用它们访问B,但似乎必须有更优雅的方法来做到这一点。我在这里想念什么?

干杯。

假设您有以下模型:

class Employee
  belongs_to :department
end
class Department
  has_many :employees
end

现在你可以根据一些部门的员工过滤

# departments with employees from California
Department.include(:employees).where(:employees => {:state => "CA"}).pluck(:name)

为了简单起见,让我们以文章和评论为例,而不是A和B。

Comment有一个指向article的外键article_id,因此我们可以设置从article到Comment的has_many关系和从Comment到article的belongs_to关系,如下所示:

class Article < ActiveRecord::Base
  has_many :comments
end
class Comment < ActiveRecord::Base
  belongs_to :article
end

一旦你有了它,你就可以执行<article>.comments了,Rails会吐出一个数组,其中包含所有带有该文章外键的注释。除非您试图设置一个更复杂的查询(例如,像在某个日期之前创建的所有注释),否则不需要使用条件语句。

要获得所有注释标题(示例中的名称),可以执行<article>.comments.map(&:title)

最新更新