有很多通过连接表 - 附加关联

时间:2012-05-01 20:28:53

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

我有一个表连接两个模型的表有很多关系。

用户通过权限有很多角色

我的权限表有三列user_id role_id firm_id

我希望每个权限(联接表)与Firms有一对一的关系。这可能吗?

---编辑或许更多的信息可以让它更清晰。

我有很多'公司'

'用户'通过'跟随'有很多公司

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

我使用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

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

先谢谢。

1 个答案:

答案 0 :(得分: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