Skip to content

Instantly share code, notes, and snippets.

@SKoschnicke
Created August 24, 2012 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SKoschnicke/3447246 to your computer and use it in GitHub Desktop.
Save SKoschnicke/3447246 to your computer and use it in GitHub Desktop.
Rails habtm extend
class Bar < ActiveRecord::Base
attr_accessible :rec_type
end
class Foo < ActiveRecord::Base
module OnePerType
def insert_record(record, force = true, validate = true)
puts "called insert record with #{record.inspect} in #{self.class}"
self.delete(*self.where(:rec_type => record.rec_type).all)
super(record,force,validate)
end
end
has_and_belongs_to_many :bars, :extend => OnePerType
end
require 'test_helper'
class FooTest < ActiveSupport::TestCase
test "only one bar per type" do
foo = Foo.create
foo.bars.insert_record Bar.create(:rec_type => "a")
foo.bars.insert_record Bar.create(:rec_type => "b")
foo.bars.insert_record Bar.create(:rec_type => "b")
foo.bars << Bar.create(:rec_type => "a")
foo.bars << Bar.create(:rec_type => "b")
foo.bars << Bar.create(:rec_type => "b")
assert_equal(2, foo.bars.size, "should have two bars")
end
end
Started
called insert record with #<Bar id: 1, rec_type: "a", created_at: "2012-08-24 07:39:10", updated_at: "2012-08-24 07:39:10"> in Array
called insert record with #<Bar id: 1, rec_type: "a", created_at: "2012-08-24 07:39:10", updated_at: "2012-08-24 07:39:10"> in ActiveRecord::Relation
E
Finished in 0.264835 seconds.
1) Error:
test_only_one_bar_per_type(FooTest):
ArgumentError: wrong number of arguments (0 for 1)
../gems/activerecord-3.2.6/lib/active_record/relation.rb:440:in `delete'
../test_extend/app/models/foo.rb:6:in `insert_record'
../gems/ruby-1.9.2-p0@rails3/gems/activerecord-3.2.6/lib/active_record/associations/collection_proxy.rb:100:in `method_missing'
../test_extend/app/models/foo.rb:7:in `insert_record'
../test_extend/test/unit/foo_test.rb:8:in `block in <class:FooTest>'
1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment