diff --git a/README.md b/README.md index 60988cf..0847da5 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/lib/mongoid/orderable.rb b/lib/mongoid/orderable.rb index c6c8514..b4fa64b 100644 --- a/lib/mongoid/orderable.rb +++ b/lib/mongoid/orderable.rb @@ -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] diff --git a/spec/mongoid/orderable_spec.rb b/spec/mongoid/orderable_spec.rb index ce04b4b..f900a07 100644 --- a/spec/mongoid/orderable_spec.rb +++ b/spec/mongoid/orderable_spec.rb @@ -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 @@ -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