Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting up Associations with DataMapper & Sinatra
    primarykey
    data
    text
    <p>Ok, so this is driving me crazy. I have read the Associations article and example and been trying to work this out for the las three days and I'm tired of this making me feel dumb, so... </p> <p>How does one set up associations with DataMapper? </p> <p>(I am using DM with Sinatra with SQLite3. Everything word fine for single tables with multiple values etc. It's when I start to try to associate them that I start getting errors.) </p> <p>Let's say I have an Orchard full of Apple Trees. Each Tree has many Apples. Each Apple has many Seeds. Therefore each tree has many Seeds through its Apples</p> <pre><code>require 'sinatra' require 'datamapper' DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/orchard.db") # Trees in the orchard. class Tree include DataMapper::Resource property :id, Serial has n, :apples has n, :seeds, :through =&gt; :apples end # Apples on a Tree. class Apple include DataMapper::Resource property :id, Serial belongs_to :tree belongs_to :seed end # Seeds in an Apple class Seed include DataMapper::Resource property :id, Serial has n, :apple has n, :tree, :through =&gt; apple end DataMapper.finalize.auto_upgrade! </code></pre> <p>Is that correct? I keep getting various errors when I try to run this. Mostly along the lines of invalid association or cannot create column NULL with value NULL etc. What am I not understanding about this relationship?</p> <p>Further, Once I have a working model how do I go about getting information from it?</p> <p>If there are 3 trees:</p> <pre><code>Tree.all.count =&gt; 3 </code></pre> <p>If there are 2 apples:</p> <pre><code>Apple.all =&gt;[#&lt;Apple @id=1&gt;, #&lt;Apple @id=2&gt;] </code></pre> <p>Ok cool. But how many Apples does Tree #2 have? How many Seeds does Tree #4 have? How many Apples in total? How many Seeds in total?</p> <p>Any help would be greatly appreciated. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload