5

I am trying to use http://compositekeys.rubyforge.org/ in order to have composite primary keys in my activerecord models.

I already added gem 'composite_primary_keys', '=3.1.0' to my Gemfile. Now I am trying to setup my first modelclass as follows.

class StringProperty < ActiveRecord::Base
    self.primary_keys :entity_id, :property_id
    set_table_name "problem.string_property"
    attr_accessible :entity_id, :property_id, :value
end

But all I get is: enter image description here

What am I doing wrong? :(

Community
  • 1
  • 1
Coxer
  • 1,694
  • 2
  • 26
  • 44

2 Answers2

10

The following will work I think.

require 'composite_primary_keys'
class StringProperty < ActiveRecord::Base
    self.primary_keys = :entity_id, :property_id
    set_table_name "problem.string_property"
    attr_accessible :entity_id, :property_id, :value
end
VenkatK
  • 1,295
  • 1
  • 9
  • 21
  • Hm, now I am getting a new error on rails server. composite_primary_keys.rb:37:in cannot load such file -- acitve_record/associations/association_prody.rb (LoadError) – Coxer Dec 13 '12 at 09:23
  • Works now for me, was using an old version (3.x.x) this caused the LoadError – Coxer Dec 13 '12 at 10:38
  • 2
    The repo is now at https://github.com/composite-primary-keys/composite_primary_keys – Chris Schmich Oct 23 '14 at 13:29
  • The documentation for the `composite_primary_keys` gem is rather sparse. I would instead suggest using Sequel, as suggested by Overbryd in https://stackoverflow.com/a/42185901/3017719. – Patrick Mar 01 '19 at 11:11
0

If it is only for unique constraint purposes use:

class Field < ActiveRecord::Base validates :input, uniqueness: { scope: :user_id, message: "one input per user" } end

source: http://guides.rubyonrails.org/active_record_validations.html

Julio Marins
  • 10,039
  • 8
  • 48
  • 54