Permalink
Browse files

auto link hm:t fixture join tables like habtm

  • Loading branch information...
1 parent 97a19c6 commit 59ba85fa5e31965130632d0c90c508693b14b086 @tenderlove tenderlove committed Sep 6, 2013
Showing with 51 additions and 0 deletions.
  1. +16 −0 activerecord/lib/active_record/fixtures.rb
  2. +35 −0 activerecord/test/cases/fixtures_test.rb
View
16 activerecord/lib/active_record/fixtures.rb
@@ -623,6 +623,10 @@ def table_rows
row[fk_name] = ActiveRecord::FixtureSet.identify(value)
end
+ when :has_many
+ if association.options[:through]
+ handle_hmt(rows, row, association)
+ end
when :has_and_belongs_to_many
handle_habtm(rows, row, association)
end
@@ -639,6 +643,18 @@ def primary_key_name
@primary_key_name ||= model_class && model_class.primary_key
end
+ def handle_hmt(rows, row, association)
+ # This is the case when the join table has no fixtures file
+ if (targets = row.delete(association.name.to_s))
+ targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
+ table_name = association.join_table
+ rows[table_name].concat targets.map { |target|
+ { association.through_reflection.foreign_key => row[primary_key_name],
+ association.foreign_key => ActiveRecord::FixtureSet.identify(target) }
+ }
+ end
+ end
+
def handle_habtm(rows, row, association)
# This is the case when the join table has no fixtures file
if (targets = row.delete(association.name.to_s))
View
35 activerecord/test/cases/fixtures_test.rb
@@ -263,6 +263,41 @@ def test_fixtures
end
end
+class HasManyThroughFixture < ActiveSupport::TestCase
+ def make_model(name)
+ Class.new(ActiveRecord::Base) { define_singleton_method(:name) { name } }
+ end
+
+ def test_has_many_through
+ pt = make_model "ParrotTreasure"
+ parrot = make_model "Parrot"
+ treasure = make_model "Treasure"
+
+ pt.table_name = "parrots_treasures"
+ pt.belongs_to :parrot, :class => parrot
+ pt.belongs_to :treasure, :class => treasure
+
+ parrot.has_many :parrot_treasures, :class => pt
+ parrot.has_many :treasures, :through => :parrot_treasures
+
+ parrots = File.join FIXTURES_ROOT, 'parrots'
+
+ fs = ActiveRecord::FixtureSet.new parrot.connection, "parrots", parrot, parrots
+ rows = fs.table_rows
+ assert_equal load_has_and_belongs_to_many['parrots_treasures'], rows['parrots_treasures']
+ end
+
+ def load_has_and_belongs_to_many
+ parrot = make_model "Parrot"
+ parrot.has_and_belongs_to_many :treasures
+
+ parrots = File.join FIXTURES_ROOT, 'parrots'
+
+ fs = ActiveRecord::FixtureSet.new parrot.connection, "parrots", parrot, parrots
+ fs.table_rows
+ end
+end
+
if Account.connection.respond_to?(:reset_pk_sequence!)
class FixturesResetPkSequenceTest < ActiveRecord::TestCase
fixtures :accounts

0 comments on commit 59ba85f

Please sign in to comment.