Mba Uchenna
Mba Uchenna

Reputation: 63

Sorting on has many association

I'm building a hotel app and I'll like to sort all hotels by the price of it's cheapest room but I can't seem to achieve my goal.

Roomtype Model>>

class Roomtype < ActiveRecord::Base
  mount_uploader :image, RimageUploader
  belongs_to :hotel
  has_many :order_items
  default_scope { order(:price => :desc)}
end

Hotel Model>>

class Hotel < ActiveRecord::Base
  has_many :roomtypes, -> { order(:price => :desc) }
  has_many :hotel_images
  belongs_to :destination
  belongs_to :area
  accepts_nested_attributes_for :hotel_images

  def price
    price = self.roomtypes.last.price
  end

end

I need a default_scope for the hotels to sort by Hotel.find(params[:id]).roomtypes.last.price

Upvotes: 0

Views: 102

Answers (3)

Mba Uchenna
Mba Uchenna

Reputation: 63

Firstly Roomtypes are sorted by price

class Roomtype < ActiveRecord::Base
    belongs_to :hotel
    default_scope { order(:price => :desc)}
end

So, the hotels last roomtype is the cheapest.

I got exactly what I wanted; sorting the list of Hotels by it's cheapest roomtype by sorting through with the use of an array

class HotelsController < ApplicationController
  def index
    @hotels = Hotel.all.sort_by{ |u| u.roomtypes.last.price }
  end
end

THIS IS THE BEST SOLUTION FOR ME!

Upvotes: 0

yatindra rao
yatindra rao

Reputation: 107

For finding all hotels sorted by cheapest total roomtype prices in ascending order.

  class Hotel < ActiveRecord::Base
    has_many :roomtypes
    default_scope { joins(:roomtypes).group("roomtypes.hotel_id").order("sum(roomtypes.price) asc") }
  end

Note: Roomtypes table is | hotel_id | price | You can change attribute names according to your code requirement.

Helped by Dixit Patel

Upvotes: 1

gates
gates

Reputation: 4613

  class Roomtype < ActiveRecord::Base
      mount_uploader :image, RimageUploader
      belongs_to :hotel
      has_many :order_items
      default_scope { order(:price => :desc)}
    end

I think the default_scope order should be ascending, since you want the prices to to be sorted from small to large.

default_scope { order(:price => :asc)}

Then Hotel.first.room_types should give you the result you wanted.

Upvotes: 0

Related Questions