Created
August 20, 2012 21:12
-
-
Save stevenklise/3407946 to your computer and use it in GitHub Desktop.
Has n, :through
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| post '/races/new' do | |
| # params = {"cars" => [ {"car_id" => 1, "duration" => 30}, {"car_id" => 2, "duration" => 40} ] } | |
| race = Race.new | |
| # Assuming that "car_id" is the same as the DB ID | |
| params["cars"].each do |car| | |
| # Here we are making a new "Racing" for each car listed in the params. See that I'm using ":car_id" and not ":car" which I showed you above. In the above ":car" accepted an entire Car model, but it can also accept just the ID of a Car by doing " | |
| race.racings << Racing.new(:car_id => car["car_id"], :duration => car["duration"]) | |
| end | |
| # If your rfid ID isn't the same as the car.id do this | |
| params["cars"].each do |car| | |
| car = Car.first(:rfid => car["rfid"]) | |
| race.racings << Racing.new(:car => car, :duration => car["duration"]) | |
| end | |
| race.save | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## DataMapper Models | |
| # Below is the example for "has n, :through" from the DataMapper page on | |
| # associations here: http://datamapper.org/docs/associations.html | |
| class Car | |
| include DataMapper::Resource | |
| has n, :racings | |
| has n, :races, :through => :racings | |
| end | |
| class Race | |
| include DataMapper::Resource | |
| property :id, Serial, :key => true | |
| has n, :racings | |
| has n, :cars, :through => :racings | |
| end | |
| class Racing | |
| include DataMapper::Resource | |
| property :id, Serial, :key => true | |
| property :duration, Integer # time duration of a race in whole numbers | |
| belongs_to :race, :key => true | |
| belongs_to :car, :key => true | |
| end | |
| ## Creating a Race etc. | |
| car1 = Car.create | |
| car2 = Car.create | |
| car3 = Car.create | |
| # Those three cars race | |
| race = Race.new | |
| race.racings # An empty array | |
| race.racings << Racing.new(:car => car1, :duration => 45) | |
| race.racings << Racing.new(:car => car2, :duration => 23) | |
| race.racings << Racing.new(:car => car3, :duration => 31) | |
| race.save | |
| race.racings # An array of 3 racing objects | |
| race.cars # An array of 3 cars that were in the race |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment