简体   繁体   English

在Rails中联接不相关的表

[英]Joining Unrelated Tables in Rails

Bottom line - I want to join two database tables together that do not "belong to" each other but do have a common field. 底线-我想加入两个数据库表一起 “属于”对方,但确实有一个共同的领域。

After some research on StackOverflow, I found some solutions to similar problems that use SQL directly, like so: 在对StackOverflow进行了一些研究之后,我找到了一些针对直接使用SQL的类似问题的解决方案,例如:

Address.joins('INNER JOIN phones on addresses.person_id = phones.person_id').select("addresses.*, phones.*").limit(1)

When I use the above statement in my rails console, however, it performs the following SQL query: 但是,当我在Rails控制台中使用上述语句时,它将执行以下SQL查询:

Address Load (0.3ms)  SELECT  addresses.*, phones.* FROM `addresses` INNER JOIN phones on addresses.person_id = phones.person_id LIMIT 1

and returns the following data (censored for privacy reasons): 并返回以下数据(出于隐私原因进行了审查):

=> #<ActiveRecord::Relation [#<Address id: 0001, created_at: "YYYY-MM-DD hh:mm:ss", updated_at: "YYYY-MM-DD hh:mm:ss", description: nil, line1: "123 Evergreen Terrace", line2: "", line3: "", city: "Springfield", state: "IL", country: "USA", zip: "11111", building_number: "001", person_id: 1, address_type: "Home", primary: false, show: nil, job_id: nil, room_number: "001", source: "HR", effective_date: "YYYY-MM-DD">]>

Not a single field from the Phone table made it into the final record. 电话表中没有一个字段使它成为最终记录。

Do I have to make these unrelated tables "belong to" each other to make them work? 为了使它们相互关联,是否必须使这些不相关的表彼此“属于”? Like - 喜欢 -

class Address < ActiveRecord::Base
  belongs_to :person
end

class Phone < ActiveRecord::Base
  belongs_to :person
  belongs_to :address
end

Or can I do what I want without modifying my models' relationships? 还是可以在不修改模型关系的情况下做我想做的事情?

The data might not be visible in the query, but the record will respond to those fields that were fetched by the query, meaining if the phone record has a number attribute for example, doing a call to .number will respond with the fetched number 数据可能在查询中不可见,但是记录将响应查询所提取的那些字段,例如,如果电话记录具有number属性,则对.number的调用将以获取的数字.number响应

address = Address.joins(....).select('*').first
address.number  # => this will print the phone number of the phone record.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM