Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
rails3mysql关系_Mysql_Ruby On Rails_Ruby On Rails 3_Relationships - Fatal编程技术网

rails3mysql关系

rails3mysql关系,mysql,ruby-on-rails,ruby-on-rails-3,relationships,Mysql,Ruby On Rails,Ruby On Rails 3,Relationships,6个月以来,我一直在使用Rails3和MySQL,但仍然不知道如何实现一个字符串列作为主键?我猜它不允许非整数字段成为MySQL中表的主键。 例如,如果我有一个customer表,其中customer_code:string作为主键,products表通过customer_code字段引用customer表,即products表中的customer_code是外键。如何在rails 3中实现这种关系? 有人能给我建议一些合适的方法来实现这种关系吗 我会保持简单,并遵循标准的rails惯例-使用自

6个月以来,我一直在使用Rails3和MySQL,但仍然不知道如何实现一个字符串列作为主键?我猜它不允许非整数字段成为MySQL中表的主键。 例如,如果我有一个customer表,其中customer_code:string作为主键,products表通过customer_code字段引用customer表,即products表中的customer_code是外键。如何在rails 3中实现这种关系?
有人能给我建议一些合适的方法来实现这种关系吗

我会保持简单,并遵循标准的rails惯例-使用自动id字段作为密钥


如果您希望在products表中包含customer_代码,以避免需要查找user对象来获取代码,那么在保存产品时也要存储该代码。

我猜您有两种型号:customer和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那样自动递增。创建前回调将帮助您。

而不是在筛选前,而是在创建前或保存前。过滤器在控制器中。
class Product < ActiveRecord::Base
  belongs_to :customer, :foreign_key => :customer_code, :primary_key => :customer_code
end