From 22473145d1b0e92eed14a4eecca2068bfed4d20a Mon Sep 17 00:00:00 2001 From: James Le Cuirot Date: Thu, 20 Sep 2012 15:15:21 +0100 Subject: [PATCH] Add scope-awareness feature --- lib/activerecord-import/import.rb | 7 +++++++ test/import_test.rb | 16 +++++++++++++++- test/test_helper.rb | 5 +++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/activerecord-import/import.rb b/lib/activerecord-import/import.rb index a596a4c..953b7ed 100644 --- a/lib/activerecord-import/import.rb +++ b/lib/activerecord-import/import.rb @@ -276,6 +276,13 @@ class ActiveRecord::Base # information on +column_names+, +array_of_attributes_ and # +options+. def import_without_validations_or_callbacks( column_names, array_of_attributes, options={} ) + scope_columns, scope_values = scope_attributes.to_a.transpose + + unless scope_columns.blank? + column_names.concat scope_columns + array_of_attributes.each { |a| a.concat scope_values } + end + columns = column_names.each_with_index.map do |name, i| column = columns_hash[name.to_s] diff --git a/test/import_test.rb b/test/import_test.rb index 982154e..efc1ee9 100644 --- a/test/import_test.rb +++ b/test/import_test.rb @@ -293,4 +293,18 @@ describe "#import" do assert_equal "2010/05/14".to_date, Topic.last.last_read.to_date end end -end \ No newline at end of file + + context "importing through an association scope" do + [ true, false ].each do |b| + context "when validation is " + (b ? "enabled" : "disabled") do + it "should automatically set the foreign key column" do + books = [[ "David Chelimsky", "The RSpec Book" ], [ "Chad Fowler", "Rails Recipes" ]] + topic = Factory.create :topic + topic.books.import [ :author_name, :title ], books, :validate => b + assert_equal 2, topic.books.count + assert topic.books.all? { |b| b.topic_id == topic.id } + end + end + end + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb index 73f2802..a28e5b4 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -44,3 +44,8 @@ adapter_schema = test_dir.join("schema/#{adapter}_schema.rb") require adapter_schema if File.exists?(adapter_schema) Dir[File.dirname(__FILE__) + "/models/*.rb"].each{ |file| require file } + +# Prevent this deprecation warning from breaking the tests. +module Rake::DeprecatedObjectDSL + remove_method :import +end