Alec Sanger
Alec Sanger

Reputation: 4562

Most efficient way to pull a specific record from an ActiveRecord collection

In my database, Account has many Contacts.

class Account < ActiveRecord::Base
    has_many :contacts
end

class Contact < ActiveRecord::Base
    belongs_to :account
end

Contacts has a field called primary_contact, which denotes the record as the primary. In a situation where I need to pull all contacts for an account, and list the primary contact separately, is there an efficient way to pull this primary record out with ActiveRecord, or should I just identify the correct record in the collection that it returns by looking at the values of that field manually?

Ideally I would like to be able to do something like account.primary_contact or even contacts.primary to identify this, but it's not necessary.

Upvotes: 0

Views: 84

Answers (2)

lurker
lurker

Reputation: 58324

class Contact < ActiveRecord::Base
    belongs_to :account
    scope :primary, where( primary_contact: true )
end

Then if you have an account:

account.contacts.primary

should give you the primary contacts.

Upvotes: 1

jvnill
jvnill

Reputation: 29599

you can add a has_one association

class Account < ActiveRecord::Base
  has_many :contacts
  has_one :primary_contact, class_name: 'Contact', conditions: { primary_contact: true }
end

UPDATE: rails 4 syntax would be

has_one :primary_contact, -> { where(primary_contact: true) }, class_name: 'Contact'

Upvotes: 1

Related Questions