【问题标题】:Rails has many through extra attributeRails 有很多通过额外的属性
【发布时间】:2015-02-26 20:57:14
【问题描述】:

我有以下关系:

# Project
has_many :teammates
has_many :users, through: :teammates

# User
has_many :teammates
has_many :projects, through: :teammates

# Teammate
belongs_to :user
belongs_to :project

teammate 表有一个“角色”字段,说明用户在项目中的角色。 这就是我在数据库中保存具有该角色的队友的方式:

project.teammates.create(:user => current_user, :role => 10)

所以这是有效的。现在我想做的是从特定项目中获取所有用户,所有用户都有一个角色字段,告诉他们在该项目中的角色。

这可能吗?我读过一些关于向用户模型添加attribute_accessible 的帖子,但这不再出现在rails 4 中。

【问题讨论】:

    标签: ruby-on-rails attributes has-many-through


    【解决方案1】:

    好的,所以我找到了解决方案here

    这行得通

    has_many :users, -> { select('users.*, teammates.role as teammate_role') }, through: :teammates
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-12
      • 2012-03-17
      • 2021-11-16
      • 2017-04-25
      • 2012-06-21
      • 2010-09-29
      • 1970-01-01
      相关资源
      最近更新 更多