glarkou
glarkou

Reputation: 7101

Easily access fields in Models

I have:

Class User < ActiveRecord::Base
 has_one :default_permission
end

class DefaultPermission < ActiveRecord::Base
 belongs_to :user
 belongs_to :permission
end

class Permission < ActiveRecord::Base
  has_many :default_permissions
end

Which is the easiest way to get default permissions for a specific user?

Using a scope? Or can I do something like user.defaultpermission.permissions ??

Thanks

Upvotes: 0

Views: 72

Answers (2)

jamesc
jamesc

Reputation: 12837

Your question is kind of contradictory You have a has_one default_permission defined but you are asking how to get all the default_permissions for a user? Whether or not I have misunderstood your question it is quite clear that you have a small design flaw If you want to get all permissions for a user then you need to define a has_many permissions with the appropriate user_id on the permission table or If you want all the default permissions then you need to change the has_one default permission to a has_many default permissions

Personally I would use roles rather than permissions and define the permissions as business logic methods on either the roles class or the person class whichever best suits your requirements

That way you can define can_do_something? methods on the user class thus a person or user or whatever can have one or many roles and the user class can_do_something? methods look at the roles and decide whether to return true or false

Upvotes: 0

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

If you have the data correctly stored, this will work:

user.default_permission.permissions 

this seems complicated thought -- it might be a sign your design is flawed.

Upvotes: 1

Related Questions