Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 4265

Show
Ignore:
Timestamp:
04/25/06 05:49:14 (3 years ago)
Author:
rick
Message:

Raise error when trying to add to a has_many :through association. Use the Join Model instead. [Rick]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activerecord/CHANGELOG

    r4264 r4265  
    11*SVN* 
     2 
     3* Raise error when trying to add to a has_many :through association. [Rick] 
     4 
     5    @post.tags << @tag                  # BAD 
     6    @post.taggings.create(:tag => @tag) # GOOD 
    27 
    38* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick] 
  • trunk/activerecord/lib/active_record/associations.rb

    r4264 r4265  
    6464    def message 
    6565      "Can not eagerly load the polymorphic association #{@reflection.name.inspect}" 
     66    end 
     67  end 
     68 
     69  class ReadOnlyAssociation < ActiveRecordError #:nodoc: 
     70    def initialize(reflection) 
     71      @reflection = reflection 
     72    end 
     73   
     74    def message 
     75      "Can not add to a has_many :through association.  Try adding to #{@reflection.through_reflection.name.inspect}." 
    6676    end 
    6777  end 
  • trunk/activerecord/lib/active_record/associations/has_many_through_association.rb

    r4169 r4265  
    88        construct_sql 
    99      end 
    10  
    1110 
    1211      def find(*args) 
     
    4039        @target = [] 
    4140        @loaded = false 
     41      end 
     42 
     43      def <<(*args) 
     44        raise ActiveRecord::ReadOnlyAssociation, @reflection 
     45      end 
     46 
     47      [:push, :concat, :create, :build].each do |method| 
     48        alias_method method, :<< 
    4249      end 
    4350 
  • trunk/activerecord/test/associations_join_model_test.rb

    r4171 r4265  
    356356  def test_has_many_through_uses_correct_attributes 
    357357    assert_nil posts(:thinking).tags.find_by_name("General").attributes["tag_id"] 
     358  end 
     359 
     360  def test_raise_error_when_adding_to_has_many_through 
     361    assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags <<     tags(:general)  } 
     362    assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.push   tags(:general)  } 
     363    assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.concat tags(:general)  } 
     364    assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.build(:name => 'foo')  } 
     365    assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.create(:name => 'foo') } 
    358366  end 
    359367