单个用户角色的Rails关系

时间:2017-03-31 13:04:51

标签: ruby-on-rails ruby devise cancancan

我目前正致力于使用RoR构建像自由职业者这样的网站,但是我被困在某个地方,我用devise生成的用户表有一个角色列,可以是管理员,客户端或自由职业者。此外,我有一个属于用户的技能表,但我不希望每个用户都有技能,除了具有自由职业者角色的用户,我该怎么做,我目前正在使用cancancan用户授权和设计认证,角色是这个或STI的最佳解决方案,你如何建议我解决这个问题,这里是一个示例代码

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable,   :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :user_roles
  has_many :skills
  has_many :skills, through: :user_skills ## I don't want all users to have skills except the users with the role of freelancer
  has_many :roles, through: :user_roles

  def role?(role)
    roles.any? { |r| r.name.underscore.to_sym == role }
  end

end

谢谢你的期待。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

class Skill < ApplicationRecord
  belongs_to :user, -> { where role: 'freelancer' }
end

请注意,这会为skills role保存freelancer,但它们仅对func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) { let affectedEvent = arrayMoved[fromIndexPath.row] arrayMoved.remove(at: fromIndexPath.row) arrayMoved.insert(affectedEvent, at: toIndexPath.row) } 可见。 您还可以使用cancancan来检查用户是否是自由职业者。