Lorenz
Lorenz

Reputation: 775

Specifying a condition for a joined table in Rails

I'm trying to sort a list of pods based on when a user joined them. The relationship between user and pod is managed by a join table called pod_users.

So I have:

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

When a user joins a pod, a record is updated in pod_users with a timestamp. I want to order the list of pods that a user belongs to based on that created_at timestamp.

Here's what I've tried based on the instructions for 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])

I've tried different versions. I've also tried:

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

But then I get duplicates because pods have multiple users and when I do the pod_users join, those additional records get returned.

Is there a simple way to do this?

Thank you.

Upvotes: 0

Views: 54

Answers (1)

Mario
Mario

Reputation: 1359

Get rid of .joins(:pod_users) and it'll work right away. Since you have has_many :pods, through: :pod_users, rails already adds pod_users to the sql query as a join when you do @user.pods. If you wanna check this out, do @user.pods.to_sql in the console.

Your stuff should work if you do:

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

Upvotes: 1

Related Questions