views:

50

answers:

2

Hello, I am quite new to ruby on rails, but I find it phantastic.

Anyway, I am currently building my model-set, so to speak. I have a model Places, generated like this:

rails generate scaffold Place name:string description:text type:string

Now I want to make a model Route between two places, holding a distance. How can I do that, I only seen how to make references to just one model so far.

Thanks for listening...

A: 

For Rails associations I would check out :

http://guides.rubyonrails.org/association_basics.html

Also, a distance is more of an attribute of a place. For example, Place.find(1).location = (x,y) and Place.find(2).location = (x,y). And then in your model, place.rb , you can write a method for distances.

def distance(first_place, second_place)
  ...
end

There is a sweet gem for that here : http://geokit.rubyforge.org/api/geokit-gem/index.html

To install type :

 sudo gem install geokit
Trip
+2  A: 

You have to create a model called Route, should look like this:

First generate with scaffold

rails g scaffold Route start_place_id:integer end_place_id:integer distance:decimal

run migrations

Then you have to set up the relations. A Place can be a start point or an end point, because the identification is not trivial by the relation, we have to specify the class and the foreign key to work properly.(in a simple has many association we can do has_many :routes, and belongs_to :place but that's not the case) route.rb

class Route<ActiveRecord::Base
 belongs_to :start_place, :class_name=>"Place", :foreign_key=>"start_place_id"
 belongs_to :end_place, :class_name=>"Place", :foreign_key=>"end_place_id
end

In your place.rb you have to add

class Place<ActiveRecord::Base
  has_many :routes_as_start, :class_name=>"Place", :foreign_key=>"start_place_id"
  has_many :routes_as_end, :class_name=>"Place", :foreign_key=>"end_place_id"
end

To build a relation, you can do like this:

route = @place.routes_as_start.build
route.end_place = Place.create
route.save

This should create a route with an end place too.

dombesz
Thanks, that helped me a lot.
Scán
If that's the solution, please select this as the right answer, by clickingon the small pipe near this post.
dombesz