【问题标题】:Extra Role column in join table in RailsRails 连接表中的额外角色列
【发布时间】:2014-01-24 10:50:17
【问题描述】:

我通过一个包含用户角色列的连接表让用户和公司处于多对多关系中。我不确定这是否是设置模型的最佳方式。

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

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


更新:

在阅读 Many-to-many relationship with the same model in rails? 之后我现在得到的东西有点不同(本身就是多对多)。

公司用户

belongs_to :company

belongs_to :user

公司

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

has_many :users, :through => :companies_users

用户

有一个:公司

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

has_many :companies, :through => :companies_users


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

【问题讨论】:

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


    【解决方案1】:

    就 ActiveRecord 关系而言,您上面的内容是正确的。如果您想阅读有关该主题的更多信息,我相信这是最好的来源:http://guides.rubyonrails.org/association_basics.html

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

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

    现在为了以 JSON 格式序列化,您应该在您的用户 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
    

    【讨论】:

      猜你喜欢
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2015-04-10
      相关资源
      最近更新 更多