我已经使用rails 3和MySQL 6个月了,但是仍然不知道如何实现一个"string“列作为主键?我猜在MySQL中不允许非整型字段作为表的主键。例如。如果我有一个主键为customer_code : string的customer表& products表通过customer_code字段引用customer表,即products表中的customer_code是外键。我如何在rails 3中实现这种关系?有没有人能给我一些合适的方法来实现这种关系?
发布于 2011-08-10 19:29:40
我会让事情变得简单,并遵循标准的rails约定--使用自动id字段作为键。
如果您希望在products表中包含customer_code,以避免查找user对象来获取代码,那么在保存产品时也要存储该代码。
发布于 2011-08-10 19:34:31
我猜你有两个模型:Costumer和Products。那么这个解决方案怎么样呢?
class Costumer < AR::Base
set_primary_key 'code'
has_many :products, :foreign_key => :costumer_code
validates :code, :presence => true
end
class Product < AR::Base
belongs_to :costumer, :foreign_key => :costumer_code
end问题是,您必须确保客户代码在创建时设置正确,因为它不像默认主键id那样是自动递增的。before_create回调将对您有所帮助。
发布于 2011-08-10 19:46:43
class Product < ActiveRecord::Base
belongs_to :customer, :foreign_key => :customer_code, :primary_key => :customer_code
endhttps://stackoverflow.com/questions/7009723
复制相似问题