我试图将Person表连接到Address表,最终目标是清除指针指向不存在的人的地址。
以下是我的地址模型:
**类地址〈应用程序记录
belongs_to:person,foreign_key:“fk_personID”
结束**
下面是我正在运行的代码:
ENV['RAILS_ENV'] ||= 'development'
require_relative './config/environment'
@address = Address.joins(:person)
.select("addresses.id,street1,people.first_name,people.last_name").limit 5
puts @address.to_sql
puts @address.inspect
@address.each do |adr|
puts "Address = " + adr.inspect
end
下面首先是SQL(来自address.to_sql),然后是输出。
SELECT addresses.id,street1,people.first_name,people.last_name FROM "addresses" INNER JOIN "people" ON "people"."id" = "addresses"."fk_personID" LIMIT 5
#<ActiveRecord::Relation [#<Address id: 2, street1: "CMR 431, Box 2837">, #<Address id: 3, street1: "1665 Ashland Bluff Way">, #<Address id: 4, street1: "56 Back St. Port Herman">, #<Address id: 6, street1: "1757 Reising Rd">, #<Address id: 7, street1: "81 Old Mill Road">]>
Address = #<Address id: 2, street1: "CMR 431, Box 2837">
Address = #<Address id: 3, street1: "1665 Ashland Bluff Way">
Address = #<Address id: 4, street1: "56 Back St. Port Herman">
Address = #<Address id: 6, street1: "1757 Reising Rd">
Address = #<Address id: 7, street1: "81 Old Mill Road">
下面是我将生成的SQL粘贴到SQLite中时得到的结果:
2|CMR 431, Box 2837|Mark|Dorn
3|1665 Ashland Bluff Way|Mark|Wild
4|56 Back St. Port Herman|Alfonse|Prince
6|1757 Reising Rd|Andrew|Rigotta
7|81 Old Mill Road|Angie|Ganno
因此,数据肯定在表中,并且可以通过SQL获得,但是当它被active_record吸收时,连接的列就消失了。
无论我做什么,我似乎都无法从程序中访问person.first_name。我在示例中使用first_name列,只是因为它很容易在输出中识别。
在过去的两天里,我试着用“包含”来代替“连接”,所有我能想到的方法都被难倒了。
1条答案
按热度按时间hmae6n7t1#
首先让我知道你的rails和ruby版本。2我在老的rails上也遇到过同样的问题。3我是如何解决的: