Skip to content
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,13 @@ class Item
include Mongoid::Orderable

# belongs_to :group
# belongs_to :drawer, :class_name => "Office::Drawer",
# :foreign_key => "legacy_drawer_key_id"

# orderable
# orderable :scope => :group, :column => :pos
# be lazy with different foreign keys
# orderable :scope => drawer, :column => :pos
# orderable :scope => lambda { |document| where(:group_id => document.group_id) }
# orderable :index => false # this one if you want specify indexes manually
# orderable :base => 0 # count position from zero as the top-most value (1 is the default value)
Expand Down
10 changes: 9 additions & 1 deletion lib/mongoid/orderable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@ def orderable options = {}
}

configuration.merge! options if options.is_a?(Hash)
configuration[:scope] = "#{configuration[:scope]}_id".to_sym if configuration[:scope].is_a?(Symbol) && configuration[:scope].to_s !~ /_id$/

if configuration[:scope].is_a?(Symbol) && configuration[:scope].to_s !~ /_id$/
scope_relation = self.relations[configuration[:scope].to_s]
if scope_relation
configuration[:scope] = scope_relation.key.to_sym
else
configuration[:scope] = "#{configuration[:scope]}_id".to_sym
end
end

field configuration[:column], orderable_field_opts(configuration)
if configuration[:index]
Expand Down
27 changes: 27 additions & 0 deletions spec/mongoid/orderable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ class Apple < Fruit
class Orange < Fruit
end

class ForeignKeyDiffersOrderable
include Mongoid::Document
include Mongoid::Orderable

belongs_to :different_scope, :class_name => "ForeignKeyDiffersOrderable",
:foreign_key => "different_orderable_id"

orderable :scope => :different_scope
end

describe SimpleOrderable do

before :each do
Expand Down Expand Up @@ -558,4 +568,21 @@ def positions
fruit2.position.should == 2
end
end

describe ForeignKeyDiffersOrderable do

it 'uses the foreign key of the relationship as scope' do
orderable1, orderable2, orderable3 = nil
parent_scope1 = ForeignKeyDiffersOrderable.create
parent_scope2 = ForeignKeyDiffersOrderable.create
expect do
orderable1 = ForeignKeyDiffersOrderable.create(:different_scope => parent_scope1)
orderable2 = ForeignKeyDiffersOrderable.create(:different_scope => parent_scope1)
orderable3 = ForeignKeyDiffersOrderable.create(:different_scope => parent_scope2)
end.to_not raise_error
expect(orderable1.position).to eq 1
expect(orderable2.position).to eq 2
expect(orderable3.position).to eq 1
end
end
end