以下はRails3.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
------一部の回避策の可能性---------
Michaelが指摘したように、新しいバージョンのRailsでは、DBの参照キーが必要です。
したがって、考えられる回避策
Phone.select("phones.*, "substring(phones.area_code, 1, 3) as area_code_id").first.zipcode
それが誰かを助けることを願っています...