Add test for collection *_ids= setter when association primary key set

Fixes casting of IDs to the data type of the association primary key,
rather than then the data type of the model's primary key. (Tests use a
string primary key on the association, rather than an int.)

Tests issue #20995
上级 15e2da65
* Raise ActiveRecord::RecordNotFound from collection `*_ids` setters
for unknown IDs with a better error message.
Changes the collection `*_ids` setters to cast provided IDs the data
type of the primary key set in the association, not the model
primary key.
*Dominic Cleal*
* For PostgreSQL >= 9.4 use `pgcrypto`'s `gen_random_uuid()` instead of
......
......@@ -68,7 +68,7 @@ def ids_reader
# Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items
def ids_writer(ids)
pk_type = reflection.primary_key_type
pk_type = reflection.association_primary_key_type
ids = Array(ids).reject(&:blank?)
ids.map! { |i| pk_type.cast(i) }
records = klass.where(reflection.association_primary_key => ids).index_by do |r|
......
......@@ -397,6 +397,10 @@ def association_primary_key(klass = nil)
options[:primary_key] || primary_key(klass || self.klass)
end
def association_primary_key_type
klass.type_for_attribute(association_primary_key)
end
def active_record_primary_key
@active_record_primary_key ||= options[:primary_key] || primary_key(active_record)
end
......
......@@ -883,6 +883,13 @@ def test_collection_singular_ids_setter_with_string_primary_keys
end
def test_collection_singular_ids_setter_with_changed_primary_key
company = companies(:first_firm)
client = companies(:first_client)
company.clients_using_primary_key_ids = [client.name]
assert_equal [client], company.clients_using_primary_key
end
def test_collection_singular_ids_setter_raises_exception_when_invalid_ids_set
company = companies(:rails_core)
ids = [Developer.first.id, -9999]
......@@ -890,6 +897,13 @@ def test_collection_singular_ids_setter_raises_exception_when_invalid_ids_set
assert_match(/Couldn't find all Developers with 'id'/, e.message)
end
def test_collection_singular_ids_setter_raises_exception_when_invalid_ids_set_with_changed_primary_key
company = companies(:first_firm)
ids = [Client.first.name, "unknown client"]
e = assert_raises(ActiveRecord::RecordNotFound) { company.clients_using_primary_key_ids = ids }
assert_match(/Couldn't find all Clients with 'name'/, e.message)
end
def test_build_a_model_from_hm_through_association_with_where_clause
assert_nothing_raised { books(:awdr).subscribers.where(nick: "marklazz").build }
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册