0

下面在 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

希望它可以帮助某人...

4

2 回答 2

0

我认为,如果可以更改模型,您应该拥有/使用一个id完全没有“商业意义”的 id 字段(称为 ),例如,不是电话号码或区号或类似的东西。

然后您可以删除该primary_key设置。

然后在该特定字段上添加唯一性验证等。

我知道它在一个 Rails 版本而不是另一个版本中工作很痛苦,但使这项工作进入未来的正确途径可能是上述。Rails 真的取决于您是否遵守约定,除非您真的详细了解其内部工作原理以覆盖它们。

于 2012-08-29T13:08:32.510 回答
0

似乎,唯一的方法是手动定义关联。

class Phone < ActiveRecord::Base
  attr_accessible :phone_number

  def zipcode
    Zipcode.where(:area_code => area_code_id)
  end

  def area_code_id
    phone_number[0..2]
  end

end
于 2012-08-29T12:50:53.540 回答