How to set up a typical users HABTM roles relationship

前端 未结 2 569
耶瑟儿~
耶瑟儿~ 2020-12-31 23:42

I\'m quite new to this and I\'m using cancan + devise for my user auth. However I\'m not really sure what it means to set up a typical users HABTM roles relationship nor do

相关标签:
2条回答
  • 2021-01-01 00:05

    The Ruby on Rails Guides are a good starting point here also this tutorial is exactly what you want

    0 讨论(0)
  • 2021-01-01 00:10

    HABTM means has and belongs to many. You basically need a table as a middle man to track multiple id's (called a through table). When referenced as a typical users HABTM roles relationship, they really mean there would be a User model, Role model, users table, roles table, and a roles_users table. Don't forget to add the the HABTM -- roles_users -- table. A typical setup follows:

    class User < ActiveRecord::Base
      has_and_belongs_to_many :roles
    end
    
    class Role < ActiveRecord::Base
      has_and_belongs_to_many :users
    end
    

    You can then use the associations like normal saying User.first.roles and Role.first.users.

    There are also a couple Railscasts on your issues.

    0 讨论(0)
提交回复
热议问题