0

I am having difficulties finding the right combination to setup my foreign keys. No matter what I do my console is still reading zip_ids when it should be zip_codes only.

I am receiving this in the console:

Zip.code(30052).users.count
  Zip Load (12.5ms)  SELECT `zips`.* FROM `zips` WHERE `zips`.`code` = 30052 LIMIT 1
   (0.3ms)  SELECT COUNT(*) FROM `users` WHERE `users`.`zip_code` = 12859
 => 0 

The issue is the second line where it is somehow pulling zip code 12859, which I never specified. This is because it is using zip_id instead of zip_code from the user table.

zip.rb:

 has_many :users,  :foreign_key => "zip_code"

user.rb :

  belongs_to :zip
4

1 回答 1

1

将代码设置为主键

class Zip < ActiveRecord::Base
  self.primary_key = 'code'
  has_many :users, foreign_key: 'zip_code'
end

不要忘记在代码列中添加唯一索引:

class AddIndexToZipsCode < ActiveRecord::Migration
  def change
    add_index :zips, :code, unique: true
  end
end

并验证唯一性code

# zip.rb
validates :code, uniqueness: true

然后你会发现一个拉链Zip.find(code)

zip_code在您的users表上添加索引。

class AddIndexToUsersZipCode < ActiveRecord::Migration
  def change
    add_index :users, :zip_code
  end
end

现在,Zip.find(code).users.count应该可以了。

要使反向关系正常工作 ( user.zip),您需要在关联中指定 foreign_key:

# user.rb
belongs_to :zip, foreign_key: :zip_code
于 2013-09-11T13:56:23.743 回答