pghtech
pghtech

Reputation: 3702

Trying to determine secure way to setup many-to-many relationship for Rails

I have User and Group models with a Membership join model (see class defs below).

I have decided, after much thought to add two attributes on the Membership model that describes the users role to the group. The application is simple enough and don't want add the complexities of additional tables for separating the group roles out.

class User < ActiveRecord::Base
  .... 
  has_many :memberships
  has_many :groups, through: memberships
end

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

class Membership < ActiveRecord::Base
  .... 
  belongs_to :user
  belongs_to :group
  attr_protected :owner, :contributor
end

However, since I have added attr_protected attributes to the join model, I can't assign the owner and contributor variables on the Membership model unless I directly create a Membership object and then assign it to the group's membership array when I create the group like so:

#Partial group create method on group controller
@group = Group.new(name: params[:group])
@membership = Membership.new(group: @group, user: @user)
@membership.owner = true
@membership.contributor = true
@group.memberships << @membership

if @group.save
  .....

I am trying to not allow mass-assignment on the owner/contributor properties.

Is there a better way of creating the user/group memberships as well as setting the membership's additional attributes securely?

Upvotes: 0

Views: 34

Answers (1)

MrTheWalrus
MrTheWalrus

Reputation: 9700

As far as I know, what you've shown is the standard way of assigning values to attributes that aren't on the mass-assignment whitelist.

I might set @membership to @group.memberships.new(:user => @user) instead of Membership.new(group: @group, user: @user), but that's mostly a matter of personal coding style. I believe you'd avoid having to use @group.memberships << @membership, but it's otherwise equivalent.

Upvotes: 1

Related Questions