【问题标题】:rails 3 mysql relationshipsrails 3 mysql关系
【发布时间】:2011-08-10 10:59:59
【问题描述】:

自 6 个月以来,我一直在使用 rails 3 和 MySQL,但仍然不知道如何将“字符串”列实现为主键?我猜它不允许非整数字段成为 MySQL 中表的主键。 例如。如果我有一个客户表,其中客户代码:字符串作为主键和产品表,它通过客户代码字段引用客户表,即产品表中的客户代码是外键。我如何在 Rails 3 中实现这种关系? 谁能建议我一些合适的方法来实现这种关系?

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-3 relationships


    【解决方案1】:

    我会保持简单并遵循标准的 rails 约定 - 使用自动 id 字段作为您的密钥。

    如果您想在 products 表中包含 customer_code 以避免需要查找用户对象来获取代码,则在保存产品时也将其存储。

    【讨论】:

      【解决方案2】:

      我猜你有两个模型:CostumerProducts。那么这个解决方案怎么样?

      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 回调将帮助您。

      【讨论】:

      • 不是before_filter,而是before_createbefore_save。过滤器在控制器中。
      【解决方案3】:
      class Product < ActiveRecord::Base
        belongs_to :customer, :foreign_key => :customer_code, :primary_key => :customer_code
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多