user1734861
user1734861

Reputation: 85

Rails: has_many WITHOUT belongs_to

I am working with RoR at the moment following some books and tutorials and it works quite well. But now I have to implement something for which I do not find any resource and I need a little help with that. Here's what I want to do: I have an application where people can log into and view things, so I have a database table called users, pretty self-explanatory. Additionally I have a table user_rights, each with an id, a name, and a description. The idea is now, that each user can have multiple rights, giving him access to different parts of the application. Thus:

class User < ActiveRecord::Base
  attr_accessible :name, :password_digest, :password, :account_nr, :password_confirmation, :email
  has_many :scope
  validates :name, presence: true, uniqueness: true
  validates :account_nr, presence: true
  validates :email, :presence => true
  has_secure_password
end

and:

class Scope < ActiveRecord::Base
  attr_accessible :name, :description
end

I do not want to have a belongs_to-relationship. I just want a small table with user rights and give each user a couple of them. But unfortunately, I have absolutely no idea how to proceed! Could anyone give me some hints?

Upvotes: 4

Views: 4199

Answers (2)

Jason Swett
Jason Swett

Reputation: 45074

I believe what you're trying to do is called authorization (which you may already know). If you're writing a custom solution, I think there's probably a good chance you're reinventing the wheel.

I would recommend spending some time with CanCan, a Rails authorization plugin written by the RailsCasts guy, to see if it meets your needs.

Upvotes: 0

ABrukish
ABrukish

Reputation: 1452

Seems like you need many-to-many association, like: user could have several rights and one right could be assigned to many users.

Upvotes: 5

Related Questions