Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
Trip and Alert model are associate like: Trip has_many alerts
Trip
Alert
has_many
I have an object like @alerts = Alert.all
@alerts = Alert.all
Now I want to find Array of unique Trip from @alerts
Array
@alerts
How can i do this ?
You can use pluck method on @alerts, paired with uniq:
pluck
uniq
@alerts.pluck(:trip_id).uniq
pluck will return an array of all Trip ids.
uniq will remove all duplicated values (i.e. ids) from the array.
The result will be an Array of unique Trip ids.
Add a comment
You could try something like:
Trip.where(id: @alerts.map(&:trip_id).uniq)
This:
@alerts.map(&:trip_id).uniq
Gives you an array of unique trip ids based on your alerts.
BTW, this gives you an ActiveRecord::Relation, not an Array.
ActiveRecord::Relation
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.