Skip to content

Commit

Permalink
Merge pull request #47566 from Shopify/do-not-use-query-constraints-i…
Browse files Browse the repository at this point in the history
…f-association-doesnt-explicitly-specifies-it

Do not use `query_constraints` if association doesn't explicitly specifies it
  • Loading branch information
eileencodes committed Mar 3, 2023
2 parents 8200a3d + f45663a commit 3771f68
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/autosave_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ def save_belongs_to_association(reflection)
def compute_primary_key(reflection, record)
if primary_key_options = reflection.options[:primary_key]
primary_key_options
elsif query_constraints = record.class.query_constraints_list
elsif reflection.options[:query_constraints] && (query_constraints = record.class.query_constraints_list)
query_constraints
else
:id
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/associations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,18 @@ def test_model_with_composite_query_constraints_has_many_association_sql
assert_match(/#{Regexp.escape(Sharded::Comment.connection.quote_table_name("sharded_comments.blog_id"))} =/, sql)
end

def test_belongs_to_association_does_not_use_parent_query_constraints_if_not_configured_to
comment = sharded_comments(:great_comment_blog_post_one)
blog_post = Sharded::BlogPost.new(blog_id: comment.blog_id, title: "Following best practices")

comment.blog_post_by_id = blog_post

comment.save

assert_predicate blog_post, :persisted?
assert_equal(blog_post, comment.blog_post_by_id)
end

def test_append_composite_foreign_key_has_many_association
blog_post = sharded_blog_posts(:great_post_blog_one)
comment = Sharded::Comment.new(body: "Great post! :clap:")
Expand Down
1 change: 1 addition & 0 deletions activerecord/test/models/sharded/comment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ class Comment < ActiveRecord::Base
query_constraints :blog_id, :id

belongs_to :blog_post, query_constraints: [:blog_id, :blog_post_id]
belongs_to :blog_post_by_id, class_name: "Sharded::BlogPost", foreign_key: :blog_post_id
belongs_to :blog
end
end

0 comments on commit 3771f68

Please sign in to comment.