diff --git a/README.md b/README.md index db09f70..14a52ba 100644 --- a/README.md +++ b/README.md @@ -255,6 +255,23 @@ User.either_joins(:profile_l, :profile_r) #=> [alice, bob] #### Either Order +The `#either_order/3` method is a base ActiveRecord querying method that will order a set of columns that may or may not exist for each record. +This works similar to how [Either Join](#either-join) works. This does not however exclude records that do not have relationships. + +```ruby +alice = User.create! +bob = User.create! +ProfileL.create!(user_id: alice.id, left_turns: 100) +ProfileR.create!(user_id: bob.id, right_turns: 50) + +User.either_order(:asc, profile_l: :left_turns, profile_r: :right_turns) #=> [bob, alice] +User.either_order(:desc, profile_l: :left_turns, profile_r: :right_turns) #=> [alice, bob] + +randy = User.create! +User.either_order(:asc, profile_l: :left_turns, profile_r: :right_turns) #=> [bob, alice, randy] +User.either_order(:desc, profile_l: :left_turns, profile_r: :right_turns) #=> [randy, alice, bob] +``` + ## Installation Add this line to your application's Gemfile: diff --git a/spec/query_methods/either_spec.rb b/spec/query_methods/either_spec.rb index 261bb22..0f72662 100644 --- a/spec/query_methods/either_spec.rb +++ b/spec/query_methods/either_spec.rb @@ -28,23 +28,31 @@ describe ".either_order/2" do it "Should not exclude anyone who does not have a relationship" do query = Person.either_order(:asc, profile_l: :likes, profile_r: :dislikes) - expect(query).to include(one, two, three) + expect(query.count).to eq(3) + expect(query[0]).to eq(two) + expect(query[1]).to eq(one) + expect(query[2]).to eq(three) end it "Should order people based on their likes and dislikes in ascended order" do query = Person.either_order(:asc, profile_l: :likes, profile_r: :dislikes).where(id: [one.id, two.id]) - expect(query).to match_array([two, one]) + expect(query.count).to eq(2) + expect(query.first).to eq(two) + expect(query.last).to eq(one) end it "Should order people based on their likes and dislikes in descending order" do query = Person.either_order(:desc, profile_l: :likes, profile_r: :dislikes).where(id: [one.id, two.id]) - expect(query).to match_array([one, two]) + expect(query.first).to eq(one) + expect(query.last).to eq(two) end context "Alias .either_order/2" do it "Should order people based on their likes and dislikes in ascended order" do query = Person.either_orders(:asc, profile_l: :likes, profile_r: :dislikes).where(id: [one.id, two.id]) - expect(query).to match_array([two, one]) + expect(query.count).to eq(2) + expect(query.first).to eq(two) + expect(query.last).to eq(one) end end end