Skip to content

Commit

Permalink
Merge pull request #61 from sascha-karnatz/allow-multiple-abilities
Browse files Browse the repository at this point in the history
Use an inner select for CanCanCan abilities
  • Loading branch information
tvdeyen authored Dec 3, 2024
2 parents bc98f48 + 4d263ea commit 2d659a0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
9 changes: 2 additions & 7 deletions lib/alchemy-pg_search.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,8 @@ def self.search(query, ability: nil)
query = ::PgSearch.multisearch(query).includes(:searchable)

if ability
# left_joins method is not usable here, because the order of the joins are incorrect
# and would result in a SQL error. We can receive the correct query order with these
# odd left join string
# Ref: https://guides.rubyonrails.org/active_record_querying.html#using-a-string-sql-fragment
query = query
.joins("LEFT JOIN alchemy_pages ON alchemy_pages.id = pg_search_documents.page_id")
.merge(Alchemy::Page.accessible_by(ability, :read))
inner_ability_select = Alchemy::Page.select(:id).merge(Alchemy::Page.accessible_by(ability, :read))
query = query.where("page_id IS NULL OR page_id IN (#{inner_ability_select.to_sql})")
end

query
Expand Down
10 changes: 10 additions & 0 deletions spec/lib/alchemy-pg_search_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,16 @@
it 'should find two pages' do
expect(result.length).to eq(2)
end

context "with other search documents" do
let!(:other_search_document) do
PgSearch::Document.new(content: "Page").save(validate: false)
end

it 'should find three pages' do
expect(result.length).to eq(3)
end
end
end
end
end
Expand Down

0 comments on commit 2d659a0

Please sign in to comment.