Using Rails association methods versus scopes

63 views Asked by At

When is it appropriate (if ever) to use association methods instead of scopes? Here's an example that I think warrants association methods over scopes:

I want to be able to get the current, complete accreditation for a user by invoking something like user.accreditations.current.

class User < ActiveRecord::Base
  has_many :accreditations do
    def current
      where(state: 'complete').order(:created_at).last
    end
  end
end

class Accreditations < ActiveRecord::Base
  belongs_to :user
end

This strategy feels better because the 'current' method is defined in the User model where it is relevant. Calling Accreditation.current isn't really relevant because there is no notion of currentness without the User to provide context.

Here is the same result using scopes:

class Accreditations < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :accreditations

  scope :current, -> { where(state: 'complete').order(:created_at).last }
end
1

There are 1 answers

0
Dudo On
class User < ActiveRecord::Base
  has_one :current_accreditation, -> { where(state: 'complete').order(:created_at).last }, source: :accreditations
end

Maybe? Seems like there a few ways to skin a cat.