Reputation: 6340
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
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