Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Ruby, with ActiveRecord what is the best way to retrieve an object that belongs_to a parent object, given some conditions?
    text
    copied!<p>In my model an <code>Organisation</code> <code>has_many :users</code>, and a <code>User</code> <code>has_and_belongs_to_many :roles</code> and a <code>Role</code> has a <code>name</code> and <code>has_and_belongs_to_many :users</code>.</p> <p>In my <code>Organisation</code> class I have a method <code>get_admin</code> that is supposed to get the <code>User</code> belonging to that <code>Organisation</code> who has the <code>Role</code> <code>'admin'</code>. Like so:</p> <pre><code>def get_admin return self.users.with_role('admin') end </code></pre> <p>Alas this returns an <code>ActiveRecord::Relation</code> object, not a <code>User</code>.</p> <p>I tried appending <code>.first</code> to the end of the line like so</p> <pre><code>def get_admin return self.users.with_role('admin').first end </code></pre> <p>But then all I get is an SQL error</p> <pre><code>ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: role.name: SELECT "users".* FROM "users" WHERE ("users".organisation_id = 2) AND (role.name == 'admin') LIMIT 1 </code></pre> <p>My schema is defined thusly:</p> <pre><code>create_table "roles", :force =&gt; true do |t| t.string "name", :null =&gt; false end create_table "users", :force =&gt; true do |t| t.string "username", :null =&gt; false t.integer "organisation_id" end create_table "roles_users", :id =&gt; false, :force =&gt; true do |t| t.integer "user_id" t.integer "role_id" end create_table "organisations", :force =&gt; true do |t| t.string "name", :null =&gt; false t.string "website", :null =&gt; false end </code></pre> <p>How would I rewrite the <code>Organisation</code>'s <code>get_admin</code> method (as follows) to return an actual <code>User</code>?</p> <pre><code>def get_admin return self.users.with_role('admin') end </code></pre> <p>Cheers</p> <p>Dave</p>
 

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