1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Fix insertion of records for hmt association with scope, fix #3548

This commit is contained in:
Ivan Antropov 2013-11-10 12:28:54 +07:00
parent fa13d8e6d9
commit ec09280765
6 changed files with 32 additions and 4 deletions

View file

@ -1,3 +1,9 @@
* Fix insertion of records via has_many_through association with scope
Fixes #3548
*Ivan Antropov*
* Checks to see if the record contains the foreign key to set the inverse automatically.
*Edo Balvers*

View file

@ -84,12 +84,16 @@ module ActiveRecord
@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

View file

@ -527,9 +527,9 @@ module ActiveRecord
#
# 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] }]

View file

@ -1095,7 +1095,19 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
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

View file

@ -16,6 +16,10 @@ module ActiveRecord
def self.connection
Post.connection
end
def self.table_name
'fake_table'
end
end
def test_construction

View file

@ -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