Ruby on Rails - Retrieve array of elements from DB with expansion

Go To StackoverFlow.com

0

I have a table called routes within my database where each route has an origin and destination. Given any origin, I want to be able to return a list of destinations that can be reached directly from this origin OR from any destination that links with this origin. How can I do this in Ruby?

def find_available_routes(origin) 
  routes = Array.new
  #each row in routes has 'origin' and 'destination'
end
2012-04-04 04:21
by jmc


1

You mean essentially any destination that can be reached with at most one "layover"?

def find_available_routes(origin)
  order_0_routes = Routes.where(:origin => origin)
  destinations = order_0_routes.map(&:destination)
  order_1_routes = Routes.where(:origin => [origin, *destinations])
end

This won't exactly be fast, but depending on the needs of your application, it should be acceptable. Caching would be a simple option.

2012-04-04 04:41
by Burke


0

I have a table called routes within my database where each route has an origin and destination. Given any origin, I want to be able to return a list of destinations that can be reached directly from this origin OR from any destination that links with this origin. How can I do this in Ruby?

def find_available_routes(origin)
  #each row in routes has 'origin' and 'destination'
  Routes.where(:origin => origin)
end

I suggest, you should go though this guides.rubyonrails - association_basics.

2012-04-04 04:32
by Jatin Ganhotra
Ads