title: How to sort incoming values from an API in Rails
body: <p>I'm still new to rails and APIs. I'm trying to sort my incoming values from an API using sort_by but I can't really figure out why is not working.</p>
  <p>as you can see bellow @results contains an array of objects in my case listings.
  When I click on the drop-down button for params[:sort], eg price it seems like I'm loosing what my params listings are so then @results in an empty array.</p>
  <p>I'm not sure how to fix this if anyone can help I'll be deeply grateful.</p>
  <h1>listings_controller</h1>
  <pre><code>class ListingsController &lt; ApplicationController
    require 'will_paginate/array'
  
    def index
      listings = params[:listings]
      beds = params[:beds]
      baths = params[:baths]
      min_price = params[:min_price]
      max_price = params[:max_price]
      sub_type = params[:sub_type]
      min_area = params[:min_area]
      max_area = params[:max_area]
      residential = params[:residential]
      rental = params[:rental]
      multifamily = params[:multifamily]
      condominium = params[:condominium]
      garage_spaces = params[:garage]
  
      search_options = [ beds, baths, min_price, max_price, sub_type, min_area, max_area, residential, rental, multifamily, condominium, garage_spaces ]
  
      if params[:sort] == 'price'
        @results = Listing.find_listings(listings).sort_by { |listing| listing.price }
      elsif params[:sort] == 'date'
        @results = Listing.find_listings(listings).sort_by { |listing| listing.list_date }
      elsif params[:sort] == 'beds'
        @results = Listing.find_listings(listings).sort_by { |listing| listing.beds }
      elsif params[:sort] == 'sqft'
        @results = Listing.find_listings(listings).sort_by { |listing| listing.area }
      elsif search_options.any? { |option| option.present? }
        @results = Listing.find_listings_wo_subtype(listings, beds, baths, min_price, max_price, residential, rental, multifamily, condominium, sub_type, min_area, max_area, garage_spaces).paginate(page: params[:page], per_page: 20)
      else
        @results = Listing.find_listings(listings).paginate(page: params[:page], per_page: 20)
      end
    end
  </code></pre>
  <h1>_listing_card.html.erb</h1>
  <pre><code>&lt;div class=&quot;container&quot;&gt;
    &lt;div class=&quot;dropdown&quot;&gt;
      &lt;button class=&quot;btn btn-info dropdown-toggle&quot; type=&quot;button&quot; id=&quot;dropdownMenuButton&quot; data-toggle=&quot;dropdown&quot; aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt;
        Sort by:
        &lt;span class=&quot;caret&quot;&gt;&lt;/span&gt;
      &lt;/button&gt;
      &lt;ul class=&quot;dropdown-menu&quot; aria-labelledby=&quot;dropdownMenuButton&quot;&gt;
        &lt;li&gt;&lt;%= link_to 'Price', listings_path(sort: 'price') %&gt;&lt;/li&gt;
        &lt;li&gt;&lt;%= link_to 'Listing Date', listings_path(sort: 'date') %&gt;&lt;/li&gt;
        &lt;li&gt;&lt;%= link_to 'Beds', listings_path(sort: 'beds') %&gt;&lt;/li&gt;
        &lt;li&gt;&lt;%= link_to 'SQFT', listings_path(sort: 'sqft') %&gt;&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  
  
  &lt;% @results.each do |listing| %&gt;
    &lt;div class=&quot;item&quot;&gt;
      &lt;div class=&quot;card-image&quot;&gt;
        &lt;% if listing.listing_images.present? %&gt;
          &lt;%= link_to image_tag(listing.listing_images[0], class: 'listing-photo'), listing_path(listing.mls_id) %&gt;
        &lt;% else %&gt;
          &lt;%= link_to image_tag('Image_not_available.png', class: 'listing-photo'), listing_path(listing.mls_id) %&gt;
        &lt;% end %&gt;
      &lt;/div&gt;
      &lt;ul class=&quot;card-details&quot;&gt;
        &lt;li class=&quot;list-unstyled price&quot;&gt;&lt;%= number_to_currency(listing.price, precision: 0) %&gt;&lt;/li&gt;
        &lt;li class=&quot;list-unstyled bold&quot;&gt;&lt;%= listing.street_number %&gt; &lt;%= listing.street %&gt; &lt;br&gt;&lt;/li&gt;
        &lt;li class=&quot;list-unstyled bold&quot;&gt;&lt;%= listing.city %&gt; &lt;%= listing.state %&gt; &lt;%= listing.postal_code %&gt;&lt;br&gt;&lt;/li&gt;
        &lt;li class=&quot;list-unstyled bold&quot;&gt;&lt;%= listing.beds %&gt; beds | &lt;%= listing.baths_full %&gt; baths | &lt;%= listing.area %&gt; sqft &lt;/li&gt;
        &lt;li class=&quot;list-unstyled bold&quot;&gt;&lt;%= &quot;Listing Date:  #{ format_date(listing.list_date) }&quot;%&gt;&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;
  &lt;% end %&gt;
  </code></pre>
  <h1>listing_service.rb</h1>
  <pre><code>class ListingService
  
    attr_reader :listings,
                :residential,
                :rental,
                :multifamily,
                :condominium,
                :sub_type,
                :min_price,
                :max_price,
                :min_area,
                :max_area,
                :baths,
                :beds,
                :garage_spaces
  
    def initialize(listings, beds = '', baths = '', min_price = '', max_price = '', residential = '', rental = '', multifamily = '', condominium = '',
                    sub_type = '', min_area = '', max_area = '', garage_spaces = '' )
      @listings    = listings
      @beds        = beds
      @baths       = baths
      @min_price   = min_price
      @max_price   = max_price
      @residential = residential
      @rental      = rental
      @multifamily = multifamily
      @condominium = condominium
      @sub_type    = sub_type
      @min_area    = min_area
      @max_area    = max_area
      @garage_spaces = garage_spaces
  
      @conn = Faraday.new(url: &quot;https://api.simplyrets.com&quot;) do |faraday|
        faraday.basic_auth(ENV['SIMPLY_RETS_API_KEY'], ENV['SIMPLY_RETS_API_SECRET'])
        faraday.adapter Faraday.default_adapter
      end
    end
  
    def find_listings
      get_url(&quot;/properties?q=#{@listings}&amp;limit=200&quot;)
    end
  
    def get_url(url)
      response = @conn.get(url)
      JSON.parse(response.body, symbolize_names: true)
    end
  
    def self.find_listings(listings)
      new(listings).find_listings
    end
  </code></pre>
  <p>end</p>
  <h1>listing.rb</h1>
  <pre><code>class Listing
  
    attr_reader :beds,
                :baths_full,
                :baths_half,
                :baths,
                :area,
                :street_number,
                :street,
                :city,
                :postal_code,
                :state,
                :price,
                :latitude,
                :longitude,
                :id,
                :mls_id,
                :listing_images,
                :roof,
                :cooling,
                :style,
                :stories,
                :fireplaces,
                :flooring,
                :heating,
                :foundation,
                :laundry_features,
                :lot_description,
                :pool,
                :sub_type,
                :interior_features,
                :lot_size,
                :area_source,
                :maintenance_expense,
                :additional_rooms,
                :exterior_features,
                :water,
                :view,
                :lot_size_area,
                :subdivision,
                :construction,
                :parking,
                :parking_leased,
                :parking_spaces,
                :parking_description,
                :lot_size_area_units,
                :type,
                :garage_spaces,
                :baths_three_quaters,
                :accessiblity,
                :year_built,
                :terms,
                :showing_instructions,
                :schools,
                :middle_school,
                :high_school,
                :elementary_school,
                :tax_year,
                :tax_anual_amount,
                :remarks,
                :association_fee,
                :association_name,
                :association_amenities,
                :list_date
  
  
    def initialize(listing)
      @beds            = listing[:property][:bedrooms]
      @baths_full      = listing[:property][:bathsFull]
      @baths_half      = listing[:property][:bathsHalf]
      @baths           = listing[:property][:bathrooms]
      @area            = listing[:property][:area]
      @street          = listing[:address][:streetName]
      @street_number   = listing[:address][:streetNumberText]
      @city            = listing[:address][:city]
      @postal_code     = listing[:address][:postalCode]
      @state           = listing[:address][:state]
      @price           = listing[:listPrice]
      @latitude        = listing[:geo][:lat]
      @longitude       = listing[:geo][:lng]
      @id              = listing[:listingId]
      @mls_id          = listing[:mlsId]
      @list_date       = listing[:listDate]
  
  
      # for property details
      @listing_images        = listing[:photos]
      @roof                  = listing[:property][:roof]
      @cooling               = listing[:property][:cooling]
      @style                 = listing[:property][:style]
      @stories               = listing[:property][:stories]
      @fireplaces            = listing[:property][:fireplaces]
      @flooring              = listing[:property][:flooring]
      @heating               = listing[:property][:heating]
      @foundation            = listing[:property][:foundation]
      @laundry_features      = listing[:property][:laundryFeatures]
      @lot_description       = listing[:property][:lotDescription]
      @pool                  = listing[:property][:pool]
      @sub_type              = listing[:property][:subType]
      @interior_features     = listing[:property][:interiorFeatures]
      @lot_size              = listing[:property][:lotSize]
      @area_source           = listing[:property][:areaSource]
      @maintenance_expense   = listing[:property][:maintenanceExpense]
      @additional_rooms      = listing[:property][:additionalRooms]
      @exterior_features     = listing[:property][:exteriorFeatures]
      @water                 = listing[:property][:water]
      @view                  = listing[:property][:view]
      @lot_size_area         = listing[:property][:lotSizeArea]
      @subdivision           = listing[:property][:subdivision]
      @construction          = listing[:property][:construction]
      @parking               = listing[:property][:parking]
      @parking_leased        = listing[:property][:parking][:leased]
      @parking_spaces        = listing[:property][:parking][:spaces]
      @parking_description   = listing[:property][:parking][:description]
      @lot_size_area_units   = listing[:property][:lotSizeAreaUnits]
      @type                  = listing[:property][:type]
      @garage_spaces         = listing[:property][:garageSpaces]
      @baths_three_quaters   = listing[:property][:bathsThreeQuarter]
      @accessiblity          = listing[:property][:accessibility]
      @year_built            = listing[:property][:yearBuilt]
      @terms                 = listing[:property][:terms]
      @showing_instructions  = listing[:property][:showingInstructions]
      @schools               = listing[:school]
      @middle_school         = listing[:school][:middleSchool]
      @high_school           = listing[:school][:highSchool]
      @elementary_school     = listing[:school][:elementarySchool]
      @tax_year              = listing[:tax][:taxYear]
      @tax_anual_amount      = listing[:tax][:taxAnualAmount]
      @remarks               = listing[:property][:remarks]
      @association_fee       = listing[:association][:fee]
      @association_name      = listing[:association][:name]
      @association_amenities = listing[:association][:amenities]
    end
  
  
    def self.find_listings(listings)
      listings = ListingService.find_listings(listings)
      listings.map do |listing|
        new(listing)
      end
    end
  end
  </code></pre>