Skip to content

Commit

Permalink
Merge pull request #686 from thriver/fix-rails-71-composite-primary-key
Browse files Browse the repository at this point in the history
fix: Support ActiveRecord 7.1 composite primary keys
  • Loading branch information
flyerhzm committed Oct 13, 2023
2 parents 6faef9d + 9b1104d commit 33b0c25
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
17 changes: 13 additions & 4 deletions lib/bullet/ext/object.rb
Expand Up @@ -9,12 +9,21 @@ def bullet_primary_key_value
return if respond_to?(:persisted?) && !persisted?

if self.class.respond_to?(:primary_keys) && self.class.primary_keys
self.class.primary_keys.map { |primary_key| send primary_key }
.join(',')
primary_key = self.class.primary_keys
elsif self.class.respond_to?(:primary_key) && self.class.primary_key
send self.class.primary_key
primary_key = self.class.primary_key
else
id
primary_key = :id
end

bullet_join_potential_composite_primary_key(primary_key)
end

private

def bullet_join_potential_composite_primary_key(primary_keys)
return send(primary_keys) unless primary_keys.is_a?(Enumerable)

primary_keys.map { |primary_key| send primary_key }.join(',')
end
end
8 changes: 7 additions & 1 deletion spec/bullet/ext/object_spec.rb
Expand Up @@ -30,12 +30,18 @@
Post.primary_key = 'id'
end

it 'should return value for multiple primary keys' do
it 'should return value for multiple primary keys from the composite_primary_key gem' do
post = Post.first
allow(Post).to receive(:primary_keys).and_return(%i[category_id writer_id])
expect(post.bullet_primary_key_value).to eq("#{post.category_id},#{post.writer_id}")
end

it 'should return value for multiple primary keys from ActiveRecord 7.1' do
post = Post.first
allow(Post).to receive(:primary_key).and_return(%i[category_id writer_id])
expect(post.bullet_primary_key_value).to eq("#{post.category_id},#{post.writer_id}")
end

it 'it should return nil for unpersisted records' do
post = Post.new(id: 123)
expect(post.bullet_primary_key_value).to be_nil
Expand Down

0 comments on commit 33b0c25

Please sign in to comment.