下面在 Rails 3.0.x 中工作,在 3.2 中没有
class Phone < ActiveRecord::Base
attr_accessible :phone_number
has_one :zipcode, :primary_key => :area_code_id, :foreign_key => :area_code
def area_code_id
phone_number[0..2]
end
end
当我打电话时:
- Phone.first.zipcode
查询总是:
- SELECT "zipcodes".* FROM "zipcodes" WHERE "zipcodes"."area_code" IS NULL LIMIT 1
- - - - 编辑 - - - -
class Zipcode < ActiveRecord::Base
attr_accessible :area_code, :city, :zip_code
has_many :phones, :finder_sql => Proc.new {"SELECT DISTINCT phones.* FROM phones WHERE '#{area_code}' = substr(phones.phone_number, 1,3);"}
end
------ 一些可能的解决方法 ---------
正如迈克尔指出的那样,在新版本的 rails 上,它需要 DB 中的引用键。
所以一个可能的解决方法
Phone.select("phones.*, "substring(phones.area_code, 1, 3) as area_code_id").first.zipcode
希望它可以帮助某人...