【问题标题】:Rails join tableRails 连接表
【发布时间】:2018-07-27 21:45:35
【问题描述】:

Rails 5.2

我有一个连接表 offer_users

class Offer < ApplicationRecord
has_and_belongs_to_many :users

class User < ApplicationRecord
has_and_belongs_to_many :offers

如何获取给定 offer.id 的所有用户?

@offer = Offer.find(params[:id])
@users = User.joins(:offers).where(id: @offer.id)

只给我第一个值。感谢支持。

【问题讨论】:

  • 不是@users = @offer.users
  • User.joins(:offers).where(id: @offer.id) - 这是不对的,因为它需要@offerid 并尝试使用此id 查找用户。你加入了:offers,但没有使用。

标签: ruby-on-rails associations


【解决方案1】:

鉴于offer_id 很简单:

users = Offer.find(offer_id).users

可选地,这里的解决方案将生成一个 sql 查询而不是两个:

users = User.joins(:offers).where(offers: { id: offer_id })

我建议您阅读these guides 了解更多信息。

【讨论】:

  • 谢谢大家..这真的很有帮助
猜你喜欢
  • 1970-01-01
  • 2012-03-01
  • 2016-12-30
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多