Search code examples
ruby-on-railsforeign-keys

Multiple primary_key for has_many relation


There is a model Company that has many Disclosure and Statement.

class Company < ActiveRecord::Base
  has_many :disclosures
  has_many :statements
end

Disclosure and Statement both have date column.

And the Statement have a method like this:

def disclosures
  Disclosure.where(date: date, company_id: company_id)
end

It work's fine. But I think this kind of relation should write by has_many notation. But I couldn't find way to use multiple primary_key with has_many.

Is there a way to use multiple primary key?


Solution

  • by default Activerecord does not support composite keys, but using the following repo you should be able to:

    github.com/composite-primary-keys/composite_primary_keys

    after that you should be able to use multiple primary keys: a small example below

    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