Skip to content

Instantly share code, notes, and snippets.

@anoldguy
Created November 19, 2012 18:53
Show Gist options
  • Save anoldguy/4112842 to your computer and use it in GitHub Desktop.
Save anoldguy/4112842 to your computer and use it in GitHub Desktop.

User

  has_many :role_assignments
  has_many :roles, :through => :role_assignments

Role

  has_many :role_assignments
  has_many :users, :through => :role_assignments

RoleAssignment

  belongs_to :user
  belongs_to :role
  validates_presence_of :role_id, :user_id
  validates_uniqueness_of :role_id, :scope => :user_id
  validates_uniqueness_of :user_id, :scope => :role_id

This

user = User.new(<params go here>)
role = Role.find_by_name("Foo")
user.roles << role    #Blows up here with invalid role_assignment (user_id == nil) (but didn't used to in Oct...)
user.save

Or This?

user = User.new(<params go here>)
role = Role.find_by_name("Foo")
user.save
user.roles << role
@ernie
Copy link

ernie commented Nov 20, 2012

Neither :)

User

  has_many :role_assignments, :inverse_of => :user
  has_many :roles, :through => :role_assignments

Role

  has_many :role_assignments, :inverse_of => :role
  has_many :users, :through => :role_assignments

RoleAssignment

  belongs_to :user
  belongs_to :role
  validates_presence_of :role, :user
  validates_uniqueness_of :role_id, :scope => :user_id
  validates_uniqueness_of :user_id, :scope => :role_id
user = User.new(<params go here>)
role = Role.find_by_name("Foo")
user.roles << role    # Should no longer blow up.
user.save

@ernie
Copy link

ernie commented Nov 20, 2012

Forgot to add I don't use v_u_of anymore. I do stuff like this:

    def save(*)
      super
    rescue ActiveRecord::RecordNotUnique
      errors.add(:base, 'Role or user is not unique')
      false
    end

@anoldguy
Copy link
Author

🤘 Nice. I completely missed inverse_of. What are the reasons behind not using v_u_of and using a super'd save?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment