Permalink
Browse files

Merge pull request #12829 from iantropov/issue_insert_via_hmt_scope_3548

Fix insertion of records for hmt association with scope

Conflicts:
	activerecord/CHANGELOG.md

Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information...
1 parent c077cbe commit 74d920de088cb403f382ab401f5337764d2f9362 @rafaelfranca rafaelfranca committed Apr 10, 2014
@@ -1,3 +1,9 @@
+* Fix insertion of records via `has_many :through` association with scope.
+
+ Fixes #3548.
+
+ *Ivan Antropov*
+
* Make possible to have an association called `records`.
Fixes #11645.
@@ -83,12 +83,16 @@ def build_through_record(record)
@through_records[record.object_id] ||= begin
ensure_mutable
- through_record = through_association.build
+ through_record = through_association.build through_scope_attributes
through_record.send("#{source_reflection.name}=", record)
through_record
end
end
+ def through_scope_attributes
+ scope.where_values_hash(through_association.reflection.name.to_s)
+ end
+
def save_through_record(record)
build_through_record(record).save!
ensure
@@ -529,9 +529,9 @@ def to_sql
#
# User.where(name: 'Oscar').where_values_hash
# # => {name: "Oscar"}
- def where_values_hash
+ def where_values_hash(relation_table_name = table_name)
equalities = where_values.grep(Arel::Nodes::Equality).find_all { |node|
- node.left.relation.name == table_name
+ node.left.relation.name == relation_table_name
}
binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]
@@ -1102,7 +1102,19 @@ def test_has_many_through_obeys_order_on_through_association
assert_equal [posts(:thinking)], person.reload.first_posts
end
- def test_has_many_through_with_includes_in_through_association_scope
+ test "has many through with includes in through association scope" do
assert_not_empty posts(:welcome).author_address_extra_with_address
end
+
+ test "insert records via has_many_through association with scope" do
+ club = Club.create!
+ member = Member.create!
+ Membership.create!(club: club, member: member)
+
+ club.favourites << member
+ assert_equal [member], club.favourites
+
+ club.reload
+ assert_equal [member], club.favourites
+ end
end
@@ -16,6 +16,10 @@ class FakeKlass < Struct.new(:table_name, :name)
def self.connection
Post.connection
end
+
+ def self.table_name
+ 'fake_table'
+ end
end
def test_construction
@@ -6,6 +6,8 @@ class Club < ActiveRecord::Base
has_one :sponsored_member, :through => :sponsor, :source => :sponsorable, :source_type => "Member"
belongs_to :category
+ has_many :favourites, -> { where(memberships: { favourite: true }) }, through: :memberships, source: :member
+
private
def private_method

0 comments on commit 74d920d

Please sign in to comment.