【问题标题】:Rails has_and_belongs_to_many collection methods not showing up on objectRails has_and_belongs_to_many 集合方法未显示在对象上
【发布时间】:2014-03-21 10:22:16
【问题描述】:

我在 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

角色 权限工作得很好,但用户 角色似乎只能以一种方式工作。我可以将用户附加到角色,但不能将角色附加到用户——用户对象上不存在收集方法。从 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。启动应用程序时,似乎由于某种原因没有建立关联。

【问题讨论】:

  • u.methods的输出是否包含roles
  • 权限肯定是程序化的吗?我的意思是,你需要一个数据库来存放它们吗?
  • @dax:不,它没有。
  • @Rich Peck:嗯,是的,我们正在改变这一点,但这不是重点。这种关系应该仍然有效。
  • 好点-感谢您的澄清:)

标签: ruby-on-rails ruby ruby-on-rails-4 has-and-belongs-to-many


【解决方案1】:

也许你应该考虑使用 has_many, :through

这是一个例子

来自 ruby​​onrails.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

更多资源:

  1. the-has-many-through-association
  2. choosing-between-has-many-through-and-has-and-belongs-to-many

【讨论】:

    【解决方案2】:

    解决了,它是非常特定于项目的。我们所有的模型都需要在多个项目中使用,因此它们存在于自己的 gem 中。结果发现在另一个位置有一个不同的用户模型取代了 gem 中的那个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      相关资源
      最近更新 更多