Syed Ali
Syed Ali

Reputation: 672

Rails relationship.build not working on Many-to-Many

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.

users <-> memberships <-> groups

require 'digest/sha2'

class User < 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 => :memberships
  attr_accessible :memberships
  accepts_nested_attributes_for :memberships
end


class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
  attr_accessible  :user, :group
end


class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through=>:memberships
end

The problem is that build is not using the attributes I'm providing, specifically for group_id. I'm pasting the output of the debugger:

(rdb:1903) @user.memberships.build(:group_id=>1)
#<Membership id: nil, user_id: 5, group_id: nil, created_at: nil, updated_at: nil>

I know the relationships/ORM mappings are good because I can do this:

(rdb:1903) @user.memberships.first.group_id=1
1
(rdb:1903) @user.memberships.first
#<Membership id: nil, user_id: 5, **group_id: 1**, created_at: nil, updated_at: nil>

I've tried this on a simple has_many demo app, and it works fine.


ANSWER: It was solved by updating memberships model to have:

attr_accessible  :user, :group, :group_id

Upvotes: 2

Views: 1240

Answers (1)

tadman
tadman

Reputation: 211590

If any of the attributes are protected, you are not able to mass-assign to them using new, build, attributes= or update_attributes. This may be blocking your group_id assignment.

Upvotes: 2

Related Questions