title: How to select unique records based on foreign key column in Rails?
body: <p>I have the following model structure in my Rails 4.1 application:</p>
  
  <p>delivery_service.rb</p>
  
  <pre><code>class DeliveryService &lt; ActiveRecord::Base
      attr_accessible :name, :description, :courier_name, :active, :country_ids
  
      has_many :prices, class_name: 'DeliveryServicePrice', dependent: :delete_all
  end
  </code></pre>
  
  <p>delivery_service_price.rb</p>
  
  <pre><code>class DeliveryServicePrice &lt; ActiveRecord::Base
  
    attr_accessible :code, :price, :description, :min_weight, :max_weight, :min_length, :max_length, 
    :min_thickness, :max_thickness, :active, :delivery_service_id
  
    belongs_to :delivery_service
  end
  </code></pre>
  
  <p>As you can see, a delivery service has many delivery service prices. I'm trying to retrieve records from the delivery service price table; <em>selecting the record with the lowest price attribute within the unique scope of the foreign key</em>, delivery_service_id (so essentially the cheapest delivery service price per delivery service).</p>
  
  <p><strong>How can I select unique records from a table, with the foreign key attribute as the scope?</strong></p>
  
  <p>I hope I've explained this enough, let me know if you need anymore information.</p>
  
  <p>Thanks</p>
  
  <p><strong>UPDATE #1:</strong></p>
  
  <p>Example of what I'm trying to achieve:</p>
  
  <p><strong>delivery_service_prices table:</strong></p>
  
  <p>id: 1, price: 2.20, delivery_service_id: 1</p>
  
  <p>id: 2, price: 10.58, delivery_service_id: 1</p>
  
  <p>id: 3, price: 4.88, delivery_service_id: 2</p>
  
  <p>id: 4, price: 1.20, delivery_service_id: 2</p>
  
  <p>id: 5, price: 14.99, delivery_service_id: 3</p>
  
  <p><strong>expected results:</strong></p>
  
  <p>id: 1, price: 2.20, delivery_service_id: 1</p>
  
  <p>id: 4, price: 1.20, delivery_service_id: 2</p>
  
  <p>id: 5, price: 14.99, delivery_service_id: 3</p>