Note that there are some explanatory texts on larger screens.

plurals
  1. POJoining nested associations, multiple level
    primarykey
    data
    text
    <p>For those of you that know rails and sql well, I'm looking for some good information you could point me to. My query is very similar to the 'Joining Nested Associations' example in this section - <a href="http://guides.rubyonrails.org/active_record_querying.html#using-array-hash-of-named-associations" rel="nofollow">http://guides.rubyonrails.org/active_record_querying.html#using-array-hash-of-named-associations</a></p> <p>My models (abbreviated) are as follows,</p> <pre><code>User has_many :products # User is 'great-grandparent' Product has_many :posts # Product is grandparent #1 Event has_many :posts # Event is grandparent #2 Post belongs_to :event Post belongs_to :product Post has_many :orders # Post is parent Order belongs_to :post # Order is great-grandchild, grandchild, &amp; child </code></pre> <p>I want to collect the orders from an event for a user (the seller), and here's my best crack at it.</p> <pre><code>class Order &lt; ActiveRecord::Base def self.collect_for_seller_and_event(user_id, event_id) self.joins(:post =&gt; [{:product =&gt; :user }, :event]).where(:post =&gt; [{:product =&gt; {:user_id =&gt; user_id}}, {:event_id =&gt; event_id}]) end </code></pre> <p>What what should this join look like?</p> <p>Should I break this up into scopes in the various models on the daisy chain?</p> <p>Just to show that I have a basic understanding here, I've been able to get my first working nested join table going (I'm pretty excited about this accomplishment)</p> <pre><code>BuyerFeedback belongs_to :order def self.from_past_events self.joins(:order =&gt; {:post =&gt; :event}).where(:order =&gt; {:post =&gt; {:event =&gt; {:date.lt =&gt; Date.today}}}) end </code></pre>
    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