Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Raise error when trying to add to a has_many :through association. Us…
…e the Join Model instead. [Rick]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4265 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
technoweenie committed Apr 25, 2006
1 parent 4251662 commit c61b10b
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
5 changes: 5 additions & 0 deletions activerecord/CHANGELOG
@@ -1,5 +1,10 @@
*SVN*

* Raise error when trying to add to a has_many :through association. [Rick]

@post.tags << @tag # BAD
@post.taggings.create(:tag => @tag) # GOOD

* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick]

* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com]
Expand Down
10 changes: 10 additions & 0 deletions activerecord/lib/active_record/associations.rb
Expand Up @@ -66,6 +66,16 @@ def message
end
end

class ReadOnlyAssociation < ActiveRecordError #:nodoc:
def initialize(reflection)
@reflection = reflection
end

def message
"Can not add to a has_many :through association. Try adding to #{@reflection.through_reflection.name.inspect}."
end
end

module Associations # :nodoc:
def self.append_features(base)
super
Expand Down
Expand Up @@ -8,7 +8,6 @@ def initialize(owner, reflection)
construct_sql
end


def find(*args)
options = Base.send(:extract_options_from_args!, args)

Expand Down Expand Up @@ -41,6 +40,14 @@ def reset
@loaded = false
end

def <<(*args)
raise ActiveRecord::ReadOnlyAssociation, @reflection
end

[:push, :concat, :create, :build].each do |method|
alias_method method, :<<
end

protected
def method_missing(method, *args, &block)
if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/associations_join_model_test.rb
Expand Up @@ -357,6 +357,14 @@ def test_has_many_through_uses_correct_attributes
assert_nil posts(:thinking).tags.find_by_name("General").attributes["tag_id"]
end

def test_raise_error_when_adding_to_has_many_through
assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags << tags(:general) }
assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.push tags(:general) }
assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.concat tags(:general) }
assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.build(:name => 'foo') }
assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.create(:name => 'foo') }
end

private
# create dynamic Post models to allow different dependency options
def find_post_with_dependency(post_id, association, association_name, dependency)
Expand Down

0 comments on commit c61b10b

Please sign in to comment.