【问题标题】:has many through join table - additional association有很多通过连接表 - 附加关联
【发布时间】:2012-05-01 20:28:53
【问题描述】:

我有一个表格,将两个模型连接成一个多条直通关系。

用户通过权限拥有许多角色

我的 Authorities 表有三列 user_id role_id firm_id

我希望每个权限(连接表)都与公司建立一对一的关系。这可能吗?

--- 编辑也许多一点信息会更清楚。

我有很多“公司”

“用户”通过“关注”拥有许多公司

“用户”也通过“权限”拥有多个“角色”

我正在使用 cancan gem 来限制用户的权限,以便他们可以关注任何公司,但他们只能编辑单个公司的详细信息。这意味着我无法在用户和公司之间创建直接的 1 对 1 关联,因为他们已经有很多通过关联 - 通过关注。 Current_user.firms 将返回他们关注的所有公司。

因此,我想将他们拥有编辑权限的公司存储在授权模型中,加入用户和角色。

https://docs.google.com/drawings/d/1CiKsUEdcS6hmKa23xsapWy33NS0Gp1f11a7TgaZbAy0/edit

这应该显示我的表格布局 - 虚线是我想要建立的关联。

目前我的模型是这样的。

class Firm < ActiveRecord::Base

has_one :authority
has_many :follows, :dependent => :destroy
has_many :users, :through => :follows

class Follow < ActiveRecord::Base
belongs_to :firm
belongs_to :user

 class User < ActiveRecord::Base
 has_many :follows, :dependent => :destroy 
 has_many :firms, :through => :follows
 has_many :roles, :through => :authorities
 has_many :authorities

 class Role < ActiveRecord::Base
 has_many :users, :through => :authorities
 has_many :authorities

class Authority < ActiveRecord::Base
 belongs_to :users
belongs_to :roles
belongs_to :firm

如果我能做到这一点,我将如何选择(在控制台中我将从中着手)一个特定的“权威”并添加一个“公司”。更进一步,我将如何阅读这个嵌套属性?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord has-many-through one-to-one


    【解决方案1】:

    我不明白为什么不这样做。你到底有什么问题?

    class Authority < ActiveRecord::Base
        belongs_to :firm
    end
    
    class Firm < ActiveRecord::Base
        has_one :authority
    end
    

    您应该能够像这样更新权威机构的firm_id:

    authority = Authority.last
    authority.firm = Firm.last # or authority.update_attribute(:firm_id, Firm.last.id)
    authority.save
    

    【讨论】:

    • 嗨罗宾,感谢您的回复,我在问题中添加了很多内容以帮助详细说明。我已经尝试按照上面的建议设置数据库,但无法移植关联。一旦将公司 ID 链接到用户和角色,我似乎无法将其添加到特定权限。
    猜你喜欢
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2012-04-29
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多