2013-01-05 32 views
1

我有许多用户与多个帖子有不同的角色。这些角色是owner,editor,viewer,none。每个用户可能只有一个角色的职位。我曾经代表这是一个通过导轨关系有许多如下:Ruby on Rails中的帖子的用户和角色

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 

凡角色属性用于指示用户对帖子里面类型的角色。 设置新角色时,我不能简单地使用<<运算符,因为它不会设置role属性。处理这种情况的首选方式是什么?我如何执行每个用户/帖子组合只有一个角色并在我的Role创建逻辑中执行此操作?

回答

1

如果用户已经分配角色,您可以检入角色的创建,在这种情况下,您可以跳过分配此角色。

unless user.roles.present? 
    user.roles.create 
end 
0

我知道您要确保任何用户在某个帖子中都不会有多个角色。如果这是你想要达到那么你只需要uniquness验证添加到您的Role模式

validates :user_id, uniqueness: {scope: :post_id, message: 'User can have one role per post'}

这将确保user_idpost_id组合将是独一无二的,你可以看到更多在轨道上引导在validation with scope

相关问题