我对 Rails 4 应用程序中的 has_and_belongs_to_many
有疑问。设置如下:
- 一个用户可以有多个角色
- 一个角色可以有多个权限
由于许多用户可以共享相同的角色,并且许多角色可以共享相同的权限,并且我不需要它们之间的特殊连接模型,我使用 has_and_belongs_to_many
来处理这两种关系。
以下是模型(去除了验证):
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
end
class Role < ActiveRecord::Base
has_and_belongs_to_many :permissions
has_and_belongs_to_many :users
end
class Permission < ActiveRecord::Base
has_and_belongs_to_many :roles
end
连接表按照约定命名:
create_table "permissions_roles" do |t|
t.integer "role_id"
t.integer "permission_id"
end
create_table "roles_users" do |t|
t.integer "role_id"
t.integer "user_id"
end
Roles <-> Permissions 效果很好,但 Users <-> Roles 似乎只能以一种方式工作。我可以将用户附加到角色,但不能将角色附加到用户——用户对象上不存在收集方法。从 Rails 控制台:
> r = Role.first # Fetch a role
> r.users # Empty list of users -- so far so good
> u = User.first # Fetch a user
> u.roles # NoMethodError: undefined method `roles' for #<User:0x007fe67562f580>
知道这里会发生什么吗?
更新:
当我从控制台运行 User.has_and_belongs_to_many :roles
时,关联设置正确,我可以毫无问题地运行 User.first.roles
。似乎由于某种原因,在引导应用程序时未建立关联。
最佳答案
也许你应该考虑使用 has_many, :through
举个例子
来自 rubyonrails.org:
class Assembly < ActiveRecord::Base
has_many :manifests
has_many :parts, through: :manifests
end
class Manifest < ActiveRecord::Base
belongs_to :assembly
belongs_to :part
end
class Part < ActiveRecord::Base
has_many :manifests
has_many :assemblies, through: :manifests
end
更多资源:
关于ruby-on-rails - Rails has_and_belongs_to_many 集合方法未显示在对象上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22556055/