1

Trip and Alert model are associate like: Trip has_many alerts

I have an object like @alerts = Alert.all

Now I want to find Array of unique Trip from @alerts

How can i do this ?

2 Answers 2

2

You can use pluck method on @alerts, paired with 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

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.

Ask question

Explore related questions

See similar questions with these tags.