Note that there are some explanatory texts on larger screens.

plurals
  1. POActiveRecord and getting unused records from a relationship, find_by_sql or named_scope?
    primarykey
    data
    text
    <p>Some context:</p> <p>I have some models that look like this</p> <p>Actor has_many Acts</p> <p>Act belongs_to Actor, belongs_to Decision</p> <p>Decision has_many Acts, belongs_to Prompt</p> <p>Prompt has_many Decisions</p> <p>What I need to do is in the ActorsController, get a random Prompt that has not been used yet of all the available Prompts.</p> <p>In my rails app, Actors are presented with prompts that give them a few choices to make. When they make a choice (Decision), that is saved in the db as an Act. </p> <p>I've tried various iterations of named_scope and find_by_sql, but none worked, and I'm not even sure if my thinking was right to begin with on them, since there are so many models at work, and I don't seem to know where to start.</p> <p>I hope this gives an idea of what I'm up against. I'd appreciate even a general pointer to form a plan of attack even.</p> <p>Thanks!</p> <p><em>edit</em></p> <p>After chewing on this for a couple hours, I've got something working but it's very messy, and my logs are filled with SQL calls, so it could definitely stand a critical eye.</p> <p>In the Prompt model:</p> <pre><code> named_scope :available, lambda { |used| { :conditions =&gt; ["id NOT IN (?)", used ] } } </code></pre> <p>In the Actor model:</p> <pre><code> def used_prompts prompts = Array.new if self.acts &amp;&amp; self.acts.length &gt;= 1 self.acts self.acts.each { |act| prompts.insert(0, act.decision.prompt.id) } return prompts.sort else return [0] end end </code></pre> <p>And in the ActorsController:</p> <pre><code>@prompt = Prompt.available(@actor.used_prompts).find(:first, :order =&gt; "RAND()") </code></pre> <p>Obviously the if block in used_prompts is one guilty party here, but I don't know a better way to deal with that since I can't do self.acts.decisions.each or some such thing. Maybe someone can school me :)</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