I have a User and a Campaign model in my rails app. A campaign has_many
users and a user has_one
campaign.
I want to order the users in the campaign by the date that they were added to it.
To do that, I created a through table called CampaignUser. I thought that I'd be able to order by the created_at
column in that table, but I couldn't see an easy way to do it. See the classes below:
class Campaign < ApplicationRecord
has_many :campaign_users
has_many :users, through: :campaign_users
end
class User < ApplicationRecord
has_one :campaign, through: :campaign_users, dependent: :destroy
end
class CampaignUser < ApplicationRecord
belongs_to :campaign
belongs_to :user
end
Ideally, I'd like to write a line like this in my Campaign class:
has_many :users, through: campaign_users, -> { order(created_at: :desc) }
Where created_at
refers to campaign_users
and not to users
. Is there a way to do that?
I could just write a method on Campaign myself to order the users manually, but then I'd have to make sure I call that method everywhere instead. It seems like there should be an easier way.
Edit:
Adding a scope to the user, as suggested in other answers is more problematic in this case. I'm looking to order users by a property of the through table, not a property of the user itself. Is there a way to write the following line, replacing email
with campaign_users.created_at
, or something similar?
has_many :users, -> { order(email: :desc) }, :through => :campaign_users