Toshi
Toshi

Reputation: 6340

Rails4; scope returns ActiveRecord_AssociationRelation not single object

I just wonder how I can return one object instead of ActiveRecord_AssociationRelation within models with scope.

For example,

scope :primary, -> { where(is_active: true).last }

which returns ActiveRecord_AssociationRelation.

So I always have to something like Account.last.credit_cards.primary.last.

How can I achieve this more efficiently?

Upvotes: 0

Views: 881

Answers (1)

Ilya
Ilya

Reputation: 13487

Your code already returns a single object. It's a good practice to return ActiveRecord_Relation instead: in this case, you can write like

YourObject.scope_1(params).scope_2.where(...)

Using limit instead of last returns ActiveRecord_Relation:

scope :primary, -> { where(is_active: true).limit(1) } 

Upvotes: 2

Related Questions