Note that there are some explanatory texts on larger screens.

plurals
  1. POscope through associations : joins and merge
    primarykey
    data
    text
    <p>I have three models : <code>User</code>, <code>Product</code> and <code>Transaction</code>. (<code>Transaction</code> belongs_to both, and <code>User</code> has many <code>Product</code> and <code>Product</code> has many <code>User</code>, through <code>Transaction</code>)</p> <p>In my <code>Transaction</code> model, I have a scope for <code>current</code> transactions :</p> <pre class="lang-rb prettyprint-override"><code>scope :current, -&gt; { where 'transactions.start_date IS NOT NULL AND transactions.end_date IS NULL' } </code></pre> <p>I want to be able to do that in the console, in order to retrieve all the products that have a <code>current</code> transaction :</p> <pre class="lang-rb prettyprint-override"><code>User.first.products.owned </code></pre> <p>In the console, I can make it happen with :</p> <pre class="lang-rb prettyprint-override"><code>User.first.products.merge(Transaction.current.ownership) </code></pre> <h2>First try</h2> <p>So I add this in my <code>Product</code> model :</p> <pre class="lang-rb prettyprint-override"><code>def self.owned merge(Transaction.current.ownership) end </code></pre> <p>I type that in the console :</p> <pre class="lang-rb prettyprint-override"><code>User.first.products.owned </code></pre> <p>But here what's rails console tells me :</p> <pre class="lang-rb prettyprint-override"><code>NoMethodError: undefined method `merge' for #&lt;Class:0x00000004e2c0f8&gt; from /home/flo/.rvm/gems/ruby-2.0.0-p195/gems/activerecord-4.0.0.rc1/lib/active_record/dynamic_matchers.rb:22:in `method_missing' </code></pre> <h2>Other try</h2> <p>If I add this in my <code>Product</code> model :</p> <pre class="lang-rb prettyprint-override"><code>def self.owned joins(:transactions).merge(Transaction.current.ownership) end </code></pre> <p>I type that in the console :</p> <pre class="lang-rb prettyprint-override"><code>User.first.products.owned </code></pre> <p>But it retrieve all products with a current transaction, and not only the first user's products with a current transaction.</p> <p>Do you have any idea of what I'm doing wrong ?</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.
 

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