从活动记录连接中获取其他列的详细信息
Getting details of other columns from active record joins
我有以下连接,我在其中获得 Review
表的所有列,但我需要添加其他列,但它没有显示其他列。
Review.joins(division: [{company: :region}, :departments, :employees]).select('reviews.id, companies.name as company, region.name, divisions.name as division).limit(10)
但我只得到 Reivews
[#<Review:0x00007ff5006bb910 id: 1>,
...
如何获得 division.id、company.name 和 region.name
您所看到的(仅 Review 对象)是您应该看到的,Rails 执行 Review、Devision、Company 等之间的连接,并为您返回该连接产生的 Review 记录.但是,选定的别名列应作为审查记录中的方法可用:
reviews = Review.joins(...)
reviews.first.company
reviews.first.division
请注意,inspect
方法不显示非列属性,因此您的控制台可能会隐藏别名列(公司、部门),但它们确实存在。
由于您似乎不仅在过滤之后还需要关联数据,因此最好将其与 eager_loading since if you try to access the associations like that you will fire n+1 queries 交换。
Review.includes(division: [{company: :region}, :departments, :employees]).select('reviews.id, companies.name as company, region.name, divisions.name as division).limit(10)
我有以下连接,我在其中获得 Review
表的所有列,但我需要添加其他列,但它没有显示其他列。
Review.joins(division: [{company: :region}, :departments, :employees]).select('reviews.id, companies.name as company, region.name, divisions.name as division).limit(10)
但我只得到 Reivews
[#<Review:0x00007ff5006bb910 id: 1>,
...
如何获得 division.id、company.name 和 region.name
您所看到的(仅 Review 对象)是您应该看到的,Rails 执行 Review、Devision、Company 等之间的连接,并为您返回该连接产生的 Review 记录.但是,选定的别名列应作为审查记录中的方法可用:
reviews = Review.joins(...)
reviews.first.company
reviews.first.division
请注意,inspect
方法不显示非列属性,因此您的控制台可能会隐藏别名列(公司、部门),但它们确实存在。
由于您似乎不仅在过滤之后还需要关联数据,因此最好将其与 eager_loading since if you try to access the associations like that you will fire n+1 queries 交换。
Review.includes(division: [{company: :region}, :departments, :employees]).select('reviews.id, companies.name as company, region.name, divisions.name as division).limit(10)