Note that there are some explanatory texts on larger screens.

plurals
  1. PORails relationship.build not working on Many-to-Many
    primarykey
    data
    text
    <p>I have three resources (slight caveat is that User is associated to Devise gem, details of which I've left out since I dont think they're relevant.</p> <p>users &lt;-> memberships &lt;-> groups</p> <p>require 'digest/sha2'</p> <pre><code>class User &lt; ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me, :memberships_attributes has_many :memberships has_many :groups, :through =&gt; :memberships attr_accessible :memberships accepts_nested_attributes_for :memberships end class Membership &lt; ActiveRecord::Base belongs_to :user belongs_to :group attr_accessible :user, :group end class Group &lt; ActiveRecord::Base has_many :memberships has_many :users, :through=&gt;:memberships end </code></pre> <p>The problem is that build is not using the attributes I'm providing, specifically for <strong>group_id</strong>. I'm pasting the output of the debugger:</p> <pre><code>(rdb:1903) @user.memberships.build(:group_id=&gt;1) #&lt;Membership id: nil, user_id: 5, group_id: nil, created_at: nil, updated_at: nil&gt; </code></pre> <p>I know the relationships/ORM mappings are good because I can do this:</p> <pre><code>(rdb:1903) @user.memberships.first.group_id=1 1 (rdb:1903) @user.memberships.first #&lt;Membership id: nil, user_id: 5, **group_id: 1**, created_at: nil, updated_at: nil&gt; </code></pre> <p>I've tried this on a simple has_many demo app, and it works fine.</p> <hr> <p><strong>ANSWER: It was solved by updating memberships model to have:</strong></p> <pre><code>attr_accessible :user, :group, :group_id </code></pre>
    singulars
    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