Composite primary keys doesn't work as foreign key.

123 views
Skip to first unread message

Damian Giebas

unread,
Jul 13, 2015, 1:31:42 PM7/13/15
to compos...@googlegroups.com
Hey i have problem with associations with composite primary keys. Look at my code

class SynchronizationReport::DataSet < ActiveRecord::Base
 
self.table_name = :data_sets
 
self.primary_keys = :id, :synchronization_report_id
 belongs_to
:synchronization_report
 has_many
:data_areas, class_name: SynchronizationReport::DataArea, dependent: :delete_all
 validates_presence_of
:synchronization_report_id, :configuration_id, :synch_time
 validates_length_of
:configuration_id, in: 2..100
end

class SynchronizationReport::DataArea < ActiveRecord::Base
 
self.table_name = :data_areas
 
self.primary_keys = :id, :data_set_id, :synchronization_report_id
  belongs_to
:data_set, foreign_key: [:data_set_id, :synchronization_report_id]
  belongs_to
:synchronization_report
  validates_inclusion_of
:status, in: %w[imported import_failed exported export_failed]
  validates_presence_of
:configuration_id, :data_set_id, :synchronization_report_id, :status, :records_files_processed
  validates_length_of
:configuration_id, in: 3..100
  validates_length_of
:status, in: 3..20
  validates_length_of
:error_type, in: 3..100, allow_nil: true
end


And this code cannot pass this simple test
  describe "data_areas relation" do
    before
(:all) do
     
(0...5).each do |i|
       
FactoryGirl.create(:data_area, data_set_id: @data_set.id[0][1], synchronization_report_id: @data_set.synchronization_report.id)
     
end
   
end

    it
{ expect( @data_set.data_areas.size ).to eq 5 }
 
end

What is wrong with this code? In database all is fine, but i can't use has_many relation to get DataArea object using this "@data_set.data_areas".

Some idea?

Best regards.

Lori M Olson

unread,
Jul 14, 2015, 1:48:04 PM7/14/15
to compos...@googlegroups.com
has_many :data_areas, class_name: SynchronizationReport::DataArea, dependent: :delete_all

You are using a class, where it wants a class name ^.  Try:

has_many :data_areas, class_name: 'SynchronizationReport::DataArea', dependent: :delete_all
Reply all
Reply to author
Forward
0 new messages