【问题标题】:Specifying a condition for a joined table in Rails在 Rails 中为连接表指定条件
【发布时间】:2015-07-20 15:31:14
【问题描述】:

我正在尝试根据用户加入的时间对 pod 列表进行排序。 user 和 pod 之间的关系由一个名为 pod_users 的连接表管理。

所以我有:

Pod.rb
has_many :pod_users, dependent: :delete_all
has_many :users, through: :pod_users

User.rb
has_many :pod_users
has_many :pods, through: :pod_users

Pod_user.rb
belongs_to :pod
belongs_to :user

当用户加入 pod 时,pod_users 中的记录会更新,并带有时间戳。我想根据 created_at 时间戳对用户所属的 pod 列表进行排序。

这是我根据specifying conditions on joined tables here 的说明尝试过的:

@pods = @user.pods.joins(:pod_users).where(pod_users: {user_id: @user.id}).order("pod_users.created_at DESC").paginate(page: params[:page])

我尝试了不同的版本。我也试过:

@pods = @user.pods.joins(:pod_users).order("pod_users.created_at DESC").paginate(page: params[:page])

但后来我得到了重复,因为 pod 有多个用户,当我加入 pod_users 时,那些额外的记录会被返回。

有没有简单的方法来做到这一点?

谢谢。

【问题讨论】:

  • 我以前没有这样做过,但你可以试试:has_many :pods, -> { group("id")}, through: :pod_users - 如果这不起作用,问题是您需要按 pod.id 分组以防止重复。

标签: mysql ruby-on-rails postgresql


【解决方案1】:

摆脱.joins(:pod_users),它会立即工作。由于您有has_many :pods, through: :pod_users,所以当您执行@user.pods 时,rails 已经将 pod_users 作为连接添加到 sql 查询中。如果您想查看此内容,请在控制台中执行 @user.pods.to_sql

如果你这样做,你的东西应该可以工作:

@pods = @user.pods.order("pod_users.created_at DESC").paginate(page: params[:page])

【讨论】:

  • 天哪。如此简单,但我花了几个小时试图弄清楚这一点。谢谢!它奏效了。
猜你喜欢
  • 1970-01-01
  • 2010-11-14
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多