Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>has_many</code> accepts a block that can define/override methods for the association. This will allow you to create a custom method for <code>&lt;&lt;</code>. I've created a small example for you, you could create build in a similar fashion.</p> <pre class="lang-rb prettyprint-override"><code># Project.rb has_many :developers, :through =&gt; :project_users, :source =&gt; :user, :conditions =&gt; "project_users.role = 'developer'" do def &lt;&lt;(developer) proxy_owner.project_users.create(:role =&gt; 'developer', :user =&gt; developer) end end </code></pre> <p>Now you can add a new developer to your your project with: <code>@project.developers &lt;&lt; @user</code> as requested. <code>@project.developers</code> gives you all the developers. </p> <p>If you have a lot of roles, it might be useful to create these has_many statements dynamically. </p> <pre class="lang-rb prettyprint-override"><code># Project.rb ROLES = ['developer','contractor'] ROLES.each do |role| self.class_eval &lt;&lt;-eos has_many :#{role.downcase}s, :through =&gt; :project_users, :source =&gt; :user, :conditions =&gt; "project_users.role = '#{role}'" do def &lt;&lt;(user) proxy_owner.project_users.create(:role =&gt; '#{role}', :user =&gt; user) end end eos end </code></pre> <p>Looking back at everything above it doesn't seem like <em>the rails way</em> of doing things. Scoping this should make it possible to get the build and create commands working without redefining everything.</p> <p>Hope this helps!</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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