简体   繁体   中英

Using Rails association methods versus scopes

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
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM