开发者

rails 3 mysql relationships

i have been working with rails 3 & MySQL since 6 months but still have no idea about how can we implement a "string" column as primary key ? i guess it does not allow a non-integer field to be a primary ke开发者_开发技巧y for table in MySQL. For eg. if i have a customer table that has customer_code : string as primary key & products table that references customer table through customer_code field i.e. customer_code in products table is foreign key. How can i implement this relationship in rails 3? Can anyone suggest me some appropriate method to implement this relationship?


I'd keep things simple and go with the standard rails conventions - use the automatic id field for your keys.

If you want to have customer_code in the products table to avoid the need to look up the user object to get the code, then store this as well when you save a product.


I guess you have two models: Costumer and Products. So how about this solution?

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

On gotcha is that you have to ensure the costumers code is set properly on creation, because it's not auto-increment like the default primary key id. A before_create callback will help you.


class Product < ActiveRecord::Base
  belongs_to :customer, :foreign_key => :customer_code, :primary_key => :customer_code
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜