Stephen
Stephen

Reputation: 3982

How to get ActiveRecord_Relation based on a ActiveRecord_Relation in rails?

I have models User Course

User.rb

has_many :courses

Course.rb

belongs_to :user

If I have a ActiveRecord_Relation @users, with a list of user.

How to get a ActiveRecord_Relation @courses, with a list of course based on @users

I know it can be done @users.each do |user| one by one. But is there a easier way to do it? like @users.courses?

Upvotes: 0

Views: 712

Answers (2)

messanjah
messanjah

Reputation: 9278

flat_map is a good solution, but won't give you an ActiveRecord::Relation.

If you would like an ActiveRecord::Relation, you could build @courses like this.

@courses = Course.where(user_id: @users.select(:id))

Upvotes: 2

Igor Belo
Igor Belo

Reputation: 738

You can use the #flat_map method from Ruby:

@users.flat_map(&:courses)

Upvotes: 3

Related Questions