Skip to content

Commit

Permalink
Merge pull request #1733 from tvdeyen/fix-content-acts-as-list-scope
Browse files Browse the repository at this point in the history
Order contents by their position in its element
  • Loading branch information
tvdeyen committed Feb 25, 2020
2 parents 45aa4ad + 48f1f35 commit d9a5f6c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 10 deletions.
8 changes: 1 addition & 7 deletions app/models/alchemy/content.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,7 @@ class Content < BaseRecord

stampable stamper_class_name: Alchemy.user_class_name

acts_as_list

# ActsAsList scope
def scope_condition
# Fixes a bug with postgresql having a wrong element_id value, if element_id is nil.
"element_id = #{element_id || 'null'} AND essence_type = '#{essence_type}'"
end
acts_as_list scope: [:element_id]

# Essence scopes
scope :essence_booleans, -> { where(essence_type: "Alchemy::EssenceBoolean") }
Expand Down
4 changes: 1 addition & 3 deletions app/models/alchemy/element.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@ class Element < BaseRecord

stampable stamper_class_name: Alchemy.user_class_name

# Content positions are scoped by their essence_type, so positions can be the same for different contents.
# In order to get contents in creation order we also order them by id.
has_many :contents, -> { order(:position, :id) }, dependent: :destroy, inverse_of: :element
has_many :contents, -> { order(:position) }, dependent: :destroy, inverse_of: :element

has_many :all_nested_elements,
-> { order(:position).not_trashed },
Expand Down
17 changes: 17 additions & 0 deletions spec/models/alchemy/element_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,23 @@ module Alchemy
end
end

describe '#contents' do
let(:element) { create(:alchemy_element) }
let!(:content1) { create(:alchemy_content, element: element) }
let!(:content2) { create(:alchemy_content, element: element) }

subject { element.contents }

before do
content1.update_column(:position, 2)
content2.update_column(:position, 1)
end

it 'are ordered by position' do
is_expected.to eq([content2, content1])
end
end

describe '#content_by_type' do
before(:each) do
@element = create(:alchemy_element, name: 'headline')
Expand Down

0 comments on commit d9a5f6c

Please sign in to comment.