Rails中连接表中的“额外角色”列

时间:2014-01-24 10:50:18

标签: ruby-on-rails-3 database-design rails-activerecord model-associations

我通过连接表拥有多对多关系中的用户和公司,该连接表具有用户角色列。我不确定这是否是建立模型的最佳方式。

现在每个用户可以根据公司拥有不同的角色,使用ActiveRecord关联设计和访问用户角色的最佳方式是什么?

我想通过JSON返回基于其当前公司的用户角色,如果他们的公司是nil或者他们的角色尚未设置(nil)则默认为某事。


更新

在阅读Many-to-many relationship with the same model in rails?之后我现在得到了什么,这有点不同(自身多对多)。

CompaniesUser

belongs_to:company

belongs_to:user

公司

has_many(:companies_users,:dependent =>:destroy)

has_many:users,:through => :companies_users

用户

has_one:company

has_many(:companies_users,:dependent =>:destroy)

has_many:companies,:through => :companies_users


感谢任何建议,因为我刚开始学习这个!

1 个答案:

答案 0 :(得分:0)

根据ActiveRecord关系,您拥有的内容是正确的。如果您想更多地了解这个主题,我相信这是最好的来源:http://guides.rubyonrails.org/association_basics.html

我发现有一个问题CompaniesUsers应该是单数形式:CompanyUser,然后在使用:companies_users的所有情况下使用::company_users

我在这里假设User的当前公司是最后一个分配的公司。

现在,为了以JSON格式序列化,您应该在User ActiveRecord中添加以下内容:

    def serializable_hash(options = nil)
      options ||= {}

      h = super(options)
      if(defined?self.company_users.last and defined?(self.company_users.last).role)
        h[:role] = (self.company_users.last).role
      else
        h[:role] = 'default_value'
      end
    end