在 Rails 中通过 has_many :through 中的中间属性查找

发布于 2024-12-06 16:34:44 字数 908 浏览 0 评论 0原文

可能的重复:
Rails has_many :through 通过连接中的额外属性查找型号

我的模型中有以下多对多设置:

class Project < ActiveRecord::Base
  has_many :projectcollaborations
  has_many :partners, :through => :projectcollaborations, :source => :partner
end

class Partner < ActiveRecord::Base
  has_many :projectcollaborations
  has_many :projects, :through => :projectcollaborations, :source => :project
end

class Projectcollaboration < ActiveRecord::Base
  belongs_to :project
  belongs_to :partner
end

我可以访问:

@partner = Partner.first
@partner.projects
@partner.projectcollaborations.find_by_myrole('creator')
....

现在我如何访问 @partner 的所有项目,其中有 myrole 创建者多对多关系表?

Possible Duplicate:
Rails has_many :through Find by Extra Attributes in Join Model

I have the following many to many setup in my model:

class Project < ActiveRecord::Base
  has_many :projectcollaborations
  has_many :partners, :through => :projectcollaborations, :source => :partner
end

class Partner < ActiveRecord::Base
  has_many :projectcollaborations
  has_many :projects, :through => :projectcollaborations, :source => :project
end

class Projectcollaboration < ActiveRecord::Base
  belongs_to :project
  belongs_to :partner
end

I can access:

@partner = Partner.first
@partner.projects
@partner.projectcollaborations.find_by_myrole('creator')
....

now how can I access the @partner's all project having myrole creator in my many-to-many relationship table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初吻给了烟 2024-12-13 16:34:44
@collaborations = @partner.projectcollaborations.includes(:projects).find_all_by_myrole('creator')
@projects = @collaborations.map &:project

也许还有另一种更漂亮、更铁路的方式,但这就是我要做的

@collaborations = @partner.projectcollaborations.includes(:projects).find_all_by_myrole('creator')
@projects = @collaborations.map &:project

maybe there is another, prettier, railsier way, but this is how i'd do it

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文