Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use an inner select for CanCanCan abilities #61

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading