Raise error when trying to add to a has_many :through association. Use the Join Model instead. [Rick]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4265 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
parent
4251662c1a
commit
c61b10b62b
@ -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]
|
||||
|
@ -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
|
||||
|
@ -8,7 +8,6 @@ def initialize(owner, reflection)
|
||||
construct_sql
|
||||
end
|
||||
|
||||
|
||||
def find(*args)
|
||||
options = Base.send(:extract_options_from_args!, args)
|
||||
|
||||
@ -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))
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user