0

My Rails model has some bad lines. In general, first error is when accessing roles variable from has_access def. And then, second is when making where action.

class Organization < ActiveRecord::Base

  has_and_belongs_to_many :organizations_users
  belongs_to :user

  validates :name, :presence => true, :length => { minimum: 4, maximum: 35 }, uniqueness: true
  roles = { :administrator => 1, :support => 2 }

  def has_access(chosen_user, role)
      self.organizations_users.where('user_id = ? and role = ?', chosen_user.id, roles[role]).exists?
  end

  def add_user(chosen_user, role)
      if !self.has_access(chosen_user, role)
          self.organizations_users.create({user_id: chosen_user.id, role: roles[role]})
      end
      has_access(chosen_user,role)
  end

end

I need also to query over organizations_users table to get information about access. How can I fix that?

ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
Haris Bašić
  • 1,383
  • 2
  • 12
  • 21

2 Answers2

0

To find or add the organization do:

def has_access(role)
  self.organizations_user.find_or_create_by_role(role)
end

This allow you to use:

user = User.has_access("administrator")

user = User.first.has_acess("administrator")

And will do a find in the table user_organizations or create a new entry if can't find one. ActiveRecord relation will take care of the user_id

Jorge de los Santos
  • 4,583
  • 1
  • 17
  • 35
0

Simplest fix would be to change

def has_access(chosen_user, role)
  where('user_id = ? and role = ?', chosen_user.id, roles[role]).exists?
end

to:

def has_access(chosen_user, role)
  Organization.where('user_id = ? and role = ?', chosen_user.id, roles[role]).exists?
end

The reason for this is the where() method is a class method and only accessible from the class itself, IE. Organization.where. BTW, I am assuming (dangerously :) ) That this where clause is used from Organization.

Tacoman667
  • 1,391
  • 9
  • 16