Reputation: 1034
I have a number of users who have different roles in relation to a numbers of posts. These roles are owner
, editor
, viewer
, none
. Each user may only have one role for a post. I have represented this as a has many through relationship in rails as follows:
class User < ActiveRecord::Base
has_many :roles
has_many :posts, :through => :roles
end
class Post < ActiveRecord::Base
has_many :roles
has_many :users, through => :roles
end
class Role < ActiveRecord::Base
attr_accessor :role
belongs_to :users
belongs_to :posts
end
Where the role attribute is used to indicate which type of role the user has on the post.
When setting a new role I cannot simply use the <<
operator as it wont set the role
attribute. What is the preferred way of handling this situation? How can I enforce that there is only one role per user / post combination and enforce this in my Role
creation logic?
Upvotes: 1
Views: 119
Reputation: 2091
I understand that you want to make sure that no user will have more than one role for a certain post. If this is what you want to achieve then you just need to add uniquness validation to your Role
mode
validates :user_id, uniqueness: {scope: :post_id, message: 'User can have one role per post'}
this will ensure that the combination of user_id
and post_id
will be unique, you can see more on rails guide on validation with scope.
Upvotes: 0
Reputation: 3005
You can check in the creation of roles for the User , if he already has a role assigned in which case you can skip assigning this role.
unless user.roles.present?
user.roles.create
end
Upvotes: 1