How to set composite key in Rails application

前端 未结 2 1316
孤街浪徒
孤街浪徒 2020-12-06 18:55

I am using \'foriegner\' gem in my application to set primary key, now i am in a situation to set composite primary key in a table.

I searched the web for this, but

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 19:49

    ActiveRecord

    There is a gem called composite_primary_keys and integrates these features quite will for ActiveRecord.

    It supports a wide array of ActiveRecord versions.

    # Gemfile
    gem 'composite_primary_keys', '='
    

    Use it like the following example:

    class Membership < ActiveRecord::Base
      self.primary_keys = :user_id, :group_id
    end
    
    membership = Membership.find([1,1])  # composite ids returns single instance
    # => "1", "group_id"=>"1"}>
    

    I am happily using it in production, keeping my schema clean and tidy.

    Better alternative: Sequel

    As always, if you are looking for a great Ruby + PostgreSQL solution, look no further than jeremyevans/sequel.

    It comes with a vast amount of features, including composite primary keys. Out of the box.

    So if you are starting a new project (on PostgreSQL obviously), save yourself the headache of ActiveRecord and go with Sequel.

    class Post < Sequel::Model
      set_primary_key [:category, :title]
    end
    

提交回复
热议问题